<template>
  <div class="task-list-panel">

    <!-- 游客模式提示 - 只在未登录且任务数量达到限制时显示 -->
    <div
      v-if="!authStore.isAuthenticated && state.tasks.length >= 3"
      class="guest-notice"
    >
      <div class="notice-content">
        <svg
          class="notice-icon"
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
        >
          <circle
            cx="12"
            cy="12"
            r="10"
            stroke="currentColor"
            stroke-width="2"
          />
          <line
            x1="12"
            y1="8"
            x2="12"
            y2="12"
            stroke="currentColor"
            stroke-width="2"
          />
          <line
            x1="12"
            y1="16"
            x2="12.01"
            y2="16"
            stroke="currentColor"
            stroke-width="2"
          />
        </svg>
        <span class="notice-text">
          游客模式最多只能创建3个任务，当前已有 {{ state.tasks.length }} 个任务
        </span>
      </div>
      <button class="notice-login-btn" @click="authStore.showLoginModal()">
        立即登录
      </button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-controls">
        <div class="search-wrapper">
          <svg
            class="search-icon"
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
          >
            <circle
              cx="11"
              cy="11"
              r="8"
              stroke="currentColor"
              stroke-width="2"
            />
            <path d="m21 21-4.35-4.35" stroke="currentColor" stroke-width="2" />
          </svg>
          <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索任务..."
            class="search-input"
            @input="handleSearch"
          />
          <button
            v-if="searchQuery"
            class="clear-search-btn"
            @click="clearSearch"
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
              <line
                x1="18"
                y1="6"
                x2="6"
                y2="18"
                stroke="currentColor"
                stroke-width="2"
              />
              <line
                x1="6"
                y1="6"
                x2="18"
                y2="18"
                stroke="currentColor"
                stroke-width="2"
              />
            </svg>
          </button>
        </div>
        
        <!-- 排序筛选控件 -->
        <div class="filter-controls">
          <!-- 排序选择器 -->
          <div class="sort-wrapper">
            <svg class="sort-icon" width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M3 6h18" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
              <path d="M7 12h10" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
              <path d="M10 18h4" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
            </svg>
            <select v-model="sortBy" class="sort-select" @change="handleSortChange">
              <option value="default">默认</option>
              <option value="createTime">创建时间</option>
              <option value="dueDate">到期时间</option>
              <option value="priority">优先级</option>
              <option value="title">标题</option>
              <option value="completed">完成状态</option>
            </select>
          </div>
          
          <!-- 排序方向 -->
          <button 
            class="sort-direction-btn" 
            @click="toggleSortDirection"
            :title="sortDirection === 'asc' ? '升序' : '降序'"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path 
                v-if="sortDirection === 'asc'"
                d="M7 14l5-5 5 5" 
                stroke="currentColor" 
                stroke-width="2" 
                stroke-linecap="round" 
                stroke-linejoin="round"
              />
              <path 
                v-else
                d="M7 10l5 5 5-5" 
                stroke="currentColor" 
                stroke-width="2" 
                stroke-linecap="round" 
                stroke-linejoin="round"
              />
            </svg>
          </button>
          
          <!-- 筛选按钮 -->
          <button 
            class="filter-btn" 
            @click="showFilterPanel = !showFilterPanel"
            :class="{ active: hasActiveFilters }"
            title="筛选"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <polygon points="22,3 2,3 10,12.46 10,19 14,21 14,12.46" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            <span v-if="hasActiveFilters" class="filter-count">{{ activeFilterCount }}</span>
          </button>
        </div>
      </div>
      
      <!-- 筛选面板 -->
      <div v-if="showFilterPanel" class="filter-panel">
        <div class="filter-row">
          <div class="filter-group">
            <label>状态</label>
            <div class="checkbox-group">
              <label class="checkbox-item">
                <input type="checkbox" v-model="filters.showCompleted" @change="applyFilters">
                <span>已完成</span>
              </label>
              <label class="checkbox-item">
                <input type="checkbox" v-model="filters.showPending" @change="applyFilters">
                <span>未完成</span>
              </label>
            </div>
          </div>
          
          <div class="filter-group">
            <label>优先级</label>
            <div class="checkbox-group">
              <label class="checkbox-item">
                <input type="checkbox" v-model="filters.priorities.high" @change="applyFilters">
                <span class="priority-high">高</span>
              </label>
              <label class="checkbox-item">
                <input type="checkbox" v-model="filters.priorities.medium" @change="applyFilters">
                <span class="priority-medium">中</span>
              </label>
              <label class="checkbox-item">
                <input type="checkbox" v-model="filters.priorities.low" @change="applyFilters">
                <span class="priority-low">低</span>
              </label>
              <!-- <label class="checkbox-item">
                <input type="checkbox" v-model="filters.priorities.none" @change="applyFilters">
                <span>无</span>
              </label> -->
            </div>
          </div>
          
          <div class="filter-group">
            <label>时间范围</label>
            <div class="date-range">
              <input type="date" v-model="filters.dateRange.start" @change="applyFilters" placeholder="开始日期">
              <span>至</span>
              <input type="date" v-model="filters.dateRange.end" @change="applyFilters" placeholder="结束日期">
            </div>
          </div>
        </div>
        
        <div class="filter-actions">
          <button class="btn btn-secondary" @click="clearFilters">清除筛选</button>
          <button class="btn btn-primary" @click="showFilterPanel = false">确定</button>
        </div>
      </div>
      
      <div v-if="searchQuery" class="search-results-info">
        找到 {{ filteredTasks.length }} 个匹配的任务
      </div>
    </div>

    <!-- 批量操作区域 -->
    <div
      v-if="
        state.currentView === 'inbox' &&
        filteredTasks.length > 0 &&
        !searchQuery
      "
      class="batch-operations"
    >
      <div class="batch-header">
        <span class="batch-title">批量操作</span>
        <div class="batch-actions">
          <select v-model="batchTargetListId" class="batch-select">
            <option value="">选择目标清单</option>
            <option v-for="list in state.lists.filter(list => !list.deleted_at)" :key="list.id" :value="list.id">
              {{ list.name }}
            </option>
          </select>
          <button
            class="btn btn-secondary batch-btn"
            @click="batchMoveToList"
            :disabled="!batchTargetListId || selectedTasks.length === 0"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
              <polyline points="14,2 14,8 20,8"></polyline>
              <line x1="16" y1="13" x2="8" y2="13"></line>
              <line x1="16" y1="17" x2="8" y2="17"></line>
              <polyline points="10,9 9,9 8,9"></polyline>
            </svg>
            移动选中任务 ({{ selectedTasks.length }})
          </button>
          <button
            class="btn btn-danger batch-btn"
            @click="confirmBatchDelete"
            :disabled="selectedTasks.length === 0"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="3,6 5,6 21,6"></polyline>
              <path d="M19,6v14a2,2,0,0,1-2,2H7a2,2,0,0,1-2-2V6m3,0V4a2,2,0,0,1,2-2h4a2,2,0,0,1,2-2v2"></path>
              <line x1="10" y1="11" x2="10" y2="17"></line>
              <line x1="14" y1="11" x2="14" y2="17"></line>
            </svg>
            删除选中任务 ({{ selectedTasks.length }})
          </button>
        </div>
      </div>
    </div>

    <!-- 任务列表 -->
    <div class="task-list">
      <div
        v-for="task in filteredTasks"
        :key="task.id"
        class="task-item"
        :class="{
          completed: task.completed,
          overdue: isOverdue(task.dueDate),
          selected: selectedTasks.includes(task.id),
        }"
        @click="openTaskDetail(task)"
      >
        <!-- 批量选择复选框（仅在收件箱视图显示） -->
        <div v-if="state.currentView === 'inbox'" class="batch-checkbox" @click.stop>
          <input
            type="checkbox"
            :id="`batch-${task.id}`"
            :checked="selectedTasks.includes(task.id)"
            @change="toggleTaskSelection(task.id)"
          />
          <label :for="`batch-${task.id}`"></label>
        </div>

        <div class="task-checkbox" @click.stop>
          <input
            type="checkbox"
            :id="`task-${task.id}`"
            :checked="task.completed"
            :disabled="task.status === 'abandoned'"
            @change="toggleTaskCompleted(task.id, $event)"
          />
          <label :for="`task-${task.id}`"></label>
        </div>
        <div class="task-content">
          <div class="task-title" v-if="editingTaskId !== task.id">
            <span 
              class="task-list-indicator" 
              :style="{ backgroundColor: getTaskListColor(task) }"
            ></span>
            {{ task.title }}
          </div>
          <input
            v-else
            v-model="editingTaskTitle"
            class="task-edit-input"
            @keyup.enter="saveTaskEdit"
            @keyup.escape="cancelTaskEdit"
            @blur="saveTaskEdit"
          />
          <div class="task-meta" v-if="editingTaskId !== task.id">
            <span 
              v-if="task.status === 'abandoned'" 
              class="abandoned-label"
            >
              已放弃
            </span>
            <span
              v-if="task.priority !== 'none'"
              class="priority-badge"
              :style="{ backgroundColor: getPriorityColor(task.priority) }"
            >
              {{ getPriorityText(task.priority) }}优先级
            </span>
            <span v-if="task.pomodoroRequired > 0" class="pomodoro-count">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none">
                <circle
                  cx="12"
                  cy="12"
                  r="10"
                  stroke="currentColor"
                  stroke-width="2"
                />
                <polyline
                  points="12,6 12,12 16,14"
                  stroke="currentColor"
                  stroke-width="2"
                />
              </svg>
              {{ task.pomodoroCompleted }}/{{ task.pomodoroRequired }}个番茄钟
            </span>
            <span
              v-if="task.dueDate"
              class="due-date"
              :class="{ overdue: isOverdue(task.dueDate) }"
            >
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none">
                <rect
                  x="3"
                  y="4"
                  width="18"
                  height="18"
                  rx="2"
                  ry="2"
                  stroke="currentColor"
                  stroke-width="2"
                />
                <line
                  x1="16"
                  y1="2"
                  x2="16"
                  y2="6"
                  stroke="currentColor"
                  stroke-width="2"
                />
                <line
                  x1="8"
                  y1="2"
                  x2="8"
                  y2="6"
                  stroke="currentColor"
                  stroke-width="2"
                />
                <line
                  x1="3"
                  y1="10"
                  x2="21"
                  y2="10"
                  stroke="currentColor"
                  stroke-width="2"
                />
              </svg>
              {{ formatDate(task.dueDate) }}
            </span>
            <span v-if="task.recurrence && task.recurrence !== 'none' && ['daily', 'weekly', 'monthly'].includes(task.recurrence)" class="recurrence">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none">
                <polyline
                  points="23,4 23,10 17,10"
                  stroke="currentColor"
                  stroke-width="2"
                />
                <polyline
                  points="1,20 1,14 7,14"
                  stroke="currentColor"
                  stroke-width="2"
                />
                <path
                  d="M20.49,9A9,9,0,0,0,5.64,5.64L1,10m22,4L18.36,18.36A9,9,0,0,1,3.51,15"
                  stroke="currentColor"
                  stroke-width="2"
                />
              </svg>
              {{ getRecurrenceText(task.recurrence) }}
            </span>
          </div>
        </div>
        <div class="task-actions" v-if="editingTaskId !== task.id">
          <button
            v-if="!task.completed && task.pomodoroRequired > 0"
            class="action-btn start-btn"
            @click.stop="startTask(task.id)"
          >           
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <polygon points="5,3 19,12 5,21" fill="currentColor" />
            </svg>
          </button>
          <button
            v-if="!task.completed && task.status !== 'abandoned'"
            class="action-btn abandon-btn"
            @click.stop="confirmAbandonTask(task)"
            title="放弃任务"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path
                d="M18 6L6 18M6 6l12 12"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg>
          </button>
          <button
            v-if="task.status === 'abandoned'"
            class="action-btn restore-btn"
            @click.stop="confirmRestoreTask(task)"
            title="恢复任务"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path
                d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
              <path
                d="M21 3v5h-5"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
              <path
                d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
              <path
                d="M3 21v-5h5"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg>
          </button>
          <button
            class="action-btn delete-btn"
            @click.stop="confirmDeleteTask(task)"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <polyline
                points="3,6 5,6 21,6"
                stroke="currentColor"
                stroke-width="2"
              />
              <path
                d="M19,6v14a2,2,0,0,1-2,2H7a2,2,0,0,1-2-2V6m3,0V4a2,2,0,0,1,2,2h4a2,2,0,0,1,2,2V6"
                stroke="currentColor"
                stroke-width="2"
              />
            </svg>
          </button>
        </div>
      </div>

      <div v-if="filteredTasks.length === 0" class="empty-state">
        <svg width="64" height="64" viewBox="0 0 24 24" fill="none">
          <path
            d="M9 11H3v4h6v-4zM21 11h-6v4h6v-4zM9 3H3v4h6V3zM21 3h-6v4h6V3z"
            stroke="currentColor"
            stroke-width="1.5"
          />
        </svg>
        <p v-if="!searchQuery">暂无任务</p>
        <p v-else>未找到匹配的任务</p>
        <span v-if="!searchQuery">添加一个新任务开始吧</span>
        <span v-else>尝试使用其他关键词搜索</span>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div
      v-if="showDeleteConfirm"
      class="dialog-overlay"
      @click="cancelDeleteTask"
    >
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>确认删除</h3>
        </div>
        <div class="dialog-body">
          <p>确定要删除任务 "{{ taskToDelete?.title }}" 吗？此操作无法撤销。</p>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="cancelDeleteTask">
            取消
          </button>
          <button class="btn btn-danger" @click="handleDeleteTask">删除</button>
        </div>
      </div>
    </div>

    <!-- 放弃任务确认对话框 -->
    <div
      v-if="showAbandonConfirm"
      class="dialog-overlay"
      @click="cancelAbandonTask"
    >
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>确认放弃</h3>
        </div>
        <div class="dialog-body">
          <p>确定要放弃任务 "{{ taskToAbandon?.title }}" 吗？放弃的任务可以在已放弃列表中查看。</p>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="cancelAbandonTask">
            取消
          </button>
          <button class="btn btn-warning" @click="handleAbandonTask">放弃</button>
        </div>
      </div>
    </div>

    <!-- 恢复任务确认对话框 -->
    <div
      v-if="showRestoreConfirm"
      class="dialog-overlay"
      @click="cancelRestoreTask"
    >
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>确认恢复</h3>
        </div>
        <div class="dialog-body">
          <p>确定要恢复任务 "{{ taskToRestore?.title }}" 吗？恢复后的任务将重新变为待完成状态。</p>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="cancelRestoreTask">
            取消
          </button>
          <button class="btn btn-primary" @click="handleRestoreTask">恢复</button>
        </div>
      </div>
    </div>

    <!-- 批量删除确认对话框 -->
    <div
      v-if="showBatchDeleteConfirm"
      class="dialog-overlay"
      @click="cancelBatchDelete"
    >
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>确认批量删除</h3>
        </div>
        <div class="dialog-body">
          <p>确定要删除选中的 {{ selectedTasks.length }} 个任务吗？此操作无法撤销。</p>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="cancelBatchDelete">
            取消
          </button>
          <button class="btn btn-danger" @click="handleBatchDelete">删除</button>
        </div>
      </div>
    </div>



    <!-- 时间验证错误对话框 -->
    <div
      v-if="showTimeValidationError"
      class="dialog-overlay"
      @click="closeTimeValidationError"
    >
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>时间设置错误</h3>
        </div>
        <div class="dialog-body">
          <p>到期时间不能早于或等于开始时间，请重新设置。</p>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-primary" @click="closeTimeValidationError">
            确定
          </button>
        </div>
      </div>
    </div>

    <!-- 任务详情对话框 -->
    <div v-if="showTaskDetail" class="modal-overlay" @click="closeTaskDetail">
      <div class="add-task-modal" @click.stop>
        <div class="modal-header">
          <h3>任务详情</h3>
          <button class="modal-close" @click="closeTaskDetail">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <line
                x1="18"
                y1="6"
                x2="6"
                y2="18"
                stroke="currentColor"
                stroke-width="2"
              />
              <line
                x1="6"
                y1="6"
                x2="18"
                y2="18"
                stroke="currentColor"
                stroke-width="2"
              />
            </svg>
          </button>
        </div>
        <div class="modal-content" v-if="selectedTask">
          <!-- 时间验证提示 -->
          <div v-if="isTimeInvalid" class="time-validation-warning">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" stroke="#f59e0b" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            <span>到期时间不能早于开始时间</span>
          </div>

          <div class="add-task-wrapper">
            <div class="add-task-input">
              <svg class="add-icon" width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path d="M9 12l2 2 4-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
              </svg>
              <input
                v-model="selectedTask.title"
                type="text"
                placeholder="输入任务标题"
              />
            </div>
          </div>

          <!-- 任务选项 -->
          <div class="task-options">
            <div class="option-row">
              <div class="option-group">
                <label>优先级</label>
                <select v-model="selectedTask.priority">
                  <option value="none">无</option>
                  <option value="low">低</option>
                  <option value="medium">中</option>
                  <option value="high">高</option>
                </select>
              </div>

              <div class="option-group">
                <label>番茄钟</label>
                <select v-model="selectedTask.pomodoroRequired">
                  <option value="0">不设置</option>
                  <option value="1">1个</option>
                  <option value="2">2个</option>
                  <option value="3">3个</option>
                  <option value="4">4个</option>
                  <option value="5">5个</option>
                  <option value="6">6个</option>
                  <option value="7">7个</option>
                  <option value="8">8个</option>
                  <option value="9">9个</option>
                  <option value="10">10个</option>
                  <option value="11">11个</option>
                  <option value="12">12个</option>
                  <option value="13">13个</option>
                  <option value="14">14个</option>
                  <option value="15">15个</option>
                  <option value="16">16个</option>
                  <option value="17">17个</option>
                  <option value="18">18个</option>
                  <option value="19">19个</option>
                  <option value="20">20个</option>
                </select>
              </div>

              <div class="option-group">
                <label>
                  重复
                  <button 
                    type="button" 
                    class="repeat-help-btn" 
                    @click="showRepeatTip = true"
                    title="了解重复功能"
                  >
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                      <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                      <path d="M9,9h0a3,3,0,0,1,6,0c0,2-3,3-3,3" stroke="currentColor" stroke-width="2"/>
                      <line x1="12" y1="17" x2="12.01" y2="17" stroke="currentColor" stroke-width="2"/>
                    </svg>
                  </button>
                </label>
                <select v-model="selectedTask.recurrence">
                  <option value="none">不重复</option>
                  <option value="daily">每日</option>
                  <option value="weekly">每周</option>
                  <option value="monthly">每月</option>
                </select>
              </div>

              <div class="option-group">
                <label>开始时间</label>
                <input 
                  :value="formatDateTimeForInput(selectedTask.startTime)" 
                  @input="updateTaskStartTime($event.target.value)"
                  type="datetime-local" 
                />
              </div>

              <div class="option-group">
                <label>到期时间</label>
                <input 
                  :value="formatDateTimeForInput(selectedTask.dueDate)" 
                  @input="updateTaskDueDate($event.target.value)"
                  type="datetime-local" 
                />
              </div>
            </div>

            <div class="option-row" style="margin-top: 15px;">
              <div class="option-group">
                <label>所属清单</label>
                <select v-model="selectedTask.listId">
                  <option value="">无清单</option>
                  <option
                    v-for="list in allLists"
                    :key="list.id"
                    :value="list.id"
                  >
                    {{ list.name }}
                  </option>
                </select>
              </div>
            </div>

            <div class="option-row" style="margin-top: 15px;">
              <div class="option-group full-width">
                <label>备注</label>
                <textarea
                  v-model="selectedTask.notes"
                  placeholder="添加备注信息"
                  rows="3"
                  style="border-radius: 8px; padding: 8px; height: 100px; border: 1px solid var(--border-color); background-color: var(--input-bg-color); color: var(--text-color);"

                ></textarea>
              </div>
            </div>
          </div>
        </div>
        
        <!-- Modal Footer -->
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeTaskDetail">
            取消
          </button>
          <button 
            class="btn btn-primary" 
            @click="saveTaskDetail"
            :disabled="isTimeInvalid"
          >
            保存
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 魔法规划弹窗 -->
  <div
    v-if="showMagicPlanningModal"
    class="modal-overlay"
  >
    <div class="magic-planning-modal" @click.stop>
      <div class="modal-header">
        <div class="modal-title">
          智能清单
        </div>
        <button class="modal-close" @click="closeMagicPlanningModal">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
            <line
              x1="18"
              y1="6"
              x2="6"
              y2="18"
              stroke="currentColor"
              stroke-width="2"
            />
            <line
              x1="6"
              y1="6"
              x2="18"
              y2="18"
              stroke="currentColor"
              stroke-width="2"
            />
          </svg>
        </button>
      </div>

      <div class="modal-content">
        <!-- 随机建议 -->
        <div class="suggestions-section">
          <h4>快速选择</h4>
          <div class="suggestion-buttons">
            <button
              v-for="suggestion in suggestions"
              :key="suggestion.id"
              class="suggestion-btn"
              :class="{ active: selectedSuggestion === suggestion.id }"
              @click="selectSuggestion(suggestion)"
            >
              <span>{{ suggestion.title }}</span>
            </button>
          </div>
        </div>

        <!-- 自定义输入 -->
        <div class="input-section">
          <textarea
            v-model="customInput"
            placeholder="请描述您想要规划的事情，比如：我想在一个月内减肥10斤"
            rows="3"
            class="custom-input"
          ></textarea>
        </div>

        <!-- 清单选项 -->
        <div class="list-options-section">
          <div class="option-item">
            <label class="switch-label">
              <input
                type="checkbox"
                v-model="createNewList"
                class="switch-input"
              />
              <span class="switch-slider"></span>
              <span class="switch-text">创建新的任务清单</span>
            </label>
            <p class="option-description">
              开启后，智能清单生成的任务将添加到一个新建的清单中，清单名称由AI自动生成
            </p>
          </div>
        </div>

        <!-- 功能说明 -->
        <div class="explanation-section">
          <div class="explanation-card">
            <svg
              class="info-icon"
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
            >
              <circle
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                stroke-width="2"
              />
              <line
                x1="12"
                y1="16"
                x2="12"
                y2="12"
                stroke="currentColor"
                stroke-width="2"
              />
              <line
                x1="12"
                y1="8"
                x2="12.01"
                y2="8"
                stroke="currentColor"
                stroke-width="2"
              />
            </svg>
            <div class="explanation-text">
              <p><strong>智能清单功能说明：</strong></p>
              <p>
                基于AI智能分析，为您的目标自动生成详细的任务清单和时间安排，让复杂的计划变得简单易行。
              </p>
            </div>
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn btn-secondary" @click="closeMagicPlanningModal">
          取消
        </button>
        <button
          class="btn btn-primary magic-generate-btn"
          @click="generateMagicPlan"
          :disabled="
            isGenerating || (!selectedSuggestion && !customInput.trim())
          "
        >
          <svg
            v-if="isGenerating"
            class="loading-icon"
            width="14"
            height="14"
            viewBox="0 0 24 24"
            fill="none"
          >
            <defs>
              <linearGradient id="loadingGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color: #667eea; stop-opacity: 1" />
                <stop offset="100%" style="stop-color: #764ba2; stop-opacity: 1" />
              </linearGradient>
            </defs>
            <circle
              cx="12"
              cy="12"
              r="10"
              stroke="currentColor"
              stroke-width="2"
              opacity="0.2"
            />
            <path
              d="M12 2a10 10 0 0 1 10 10"
              stroke="url(#loadingGradient)"
              stroke-width="2.5"
              stroke-linecap="round"
            >
              <animateTransform
                attributeName="transform"
                type="rotate"
                dur="1s"
                repeatCount="indefinite"
                values="0 12 12;360 12 12"
              />
            </path>
          </svg>
          <svg
            v-else
            class="magic-wand"
            width="25"
            height="25"
            viewBox="0 0 24 24"
            fill="none"
          >
            <defs>
              <linearGradient id="wandGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color: #667eea; stop-opacity: 1" />
                <stop offset="100%" style="stop-color: #764ba2; stop-opacity: 1" />
              </linearGradient>
              <linearGradient id="wandStarGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color: #ffecd2; stop-opacity: 1" />
                <stop offset="100%" style="stop-color: #fcb69f; stop-opacity: 1" />
              </linearGradient>
            </defs>
            <path
              d="M4 20L20 4"
              stroke="url(#wandGradient)"
              stroke-width="2"
              stroke-linecap="round"
            />
            <g transform="translate(18, 6)">
              <path
                d="M0,-2 L0.6,-0.6 L2,0 L0.6,0.6 L0,2 L-0.6,0.6 L-2,0 L-0.6,-0.6 Z"
                fill="url(#wandStarGradient)"
              />
            </g>
          </svg>
          {{ isGenerating ? "生成中..." : "开始生成清单" }}
        </button>
      </div>
    </div>
  </div>

  <!-- 游客模式限制弹窗 -->
  <div
    v-if="showGuestLimitModal"
    class="modal-overlay"
  >
    <div class="guest-limit-modal" @click.stop>
      <div class="modal-header">
        <div class="modal-title">
          <svg
            class="warning-icon"
            width="20"
            height="20"
            viewBox="0 0 24 24"
            fill="none"
          >
            <path
              d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"
              stroke="currentColor"
              stroke-width="2"
              fill="none"
            />
            <line
              x1="12"
              y1="9"
              x2="12"
              y2="13"
              stroke="currentColor"
              stroke-width="2"
            />
            <line
              x1="12"
              y1="17"
              x2="12.01"
              y2="17"
              stroke="currentColor"
              stroke-width="2"
            />
          </svg>
          任务数量限制
        </div>
        <button class="modal-close" @click="closeGuestLimitModal">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
            <line
              x1="18"
              y1="6"
              x2="6"
              y2="18"
              stroke="currentColor"
              stroke-width="2"
            />
            <line
              x1="6"
              y1="6"
              x2="18"
              y2="18"
              stroke="currentColor"
              stroke-width="2"
            />
          </svg>
        </button>
      </div>
      <div class="modal-content">
        <div class="limit-info">
          <p class="limit-message">
            游客模式最多只能创建 <strong>3个任务</strong>
          </p>
          <p class="current-count">
            您当前已创建了
            <span class="count-number">{{ state.tasks.length }}</span> 个任务
          </p>
        </div>
        <div class="benefits-list">
          <h4>登录后您可以：</h4>
          <ul>
            <li>✨ 创建无限数量的任务</li>
            <li>📱 多设备同步数据</li>
            <li>🔒 数据安全保障</li>
            <li>🎯 更多高级功能</li>
          </ul>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" @click="closeGuestLimitModal">
          稍后再说
        </button>
        <button class="btn btn-primary" @click="handleGuestLogin">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <path
              d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"
              stroke="currentColor"
              stroke-width="2"
              fill="none"
            />
            <polyline
              points="10,17 15,12 10,7"
              stroke="currentColor"
              stroke-width="2"
              fill="none"
            />
            <line
              x1="15"
              y1="12"
              x2="3"
              y2="12"
              stroke="currentColor"
              stroke-width="2"
            />
          </svg>
          立即登录
        </button>
      </div>
    </div>
  </div>

  <!-- AI配置提示模态框 -->
  <div v-if="showAiConfigPrompt" class="modal-overlay">
    <div class="ai-config-prompt-modal" @click.stop>
      <div class="modal-header">
        <h3>AI功能需要配置</h3>
        <button class="close-btn" @click="showAiConfigPrompt = false">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
        </button>
      </div>
      <div class="modal-content">
        <div class="prompt-icon">
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.58L19 8l-9 9z" fill="#4CAF50"/>
          </svg>
        </div>
        <p class="prompt-message">
          要使用智能清单功能，需要先配置AI模型参数（API地址、模型名称、API密钥）。
        </p>
        <p class="prompt-submessage">
          配置完成后，您就可以使用AI来智能生成任务清单了！
        </p>
      </div>
      <div class="modal-actions">
        <button class="cancel-btn" @click="showAiConfigPrompt = false">
          稍后配置
        </button>
        <button class="confirm-btn" @click="goToSettings">
          立即配置
        </button>
      </div>
    </div>
  </div>

  <!-- AI错误提示模态框 -->
  <div v-if="showAiErrorModal" class="modal-overlay">
    <div class="ai-error-modal" @click.stop>
      <div class="modal-header">
        <div class="modal-title">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" class="error-icon">
            <circle cx="12" cy="12" r="10" stroke="#ef4444" stroke-width="2" fill="none"/>
            <line x1="15" y1="9" x2="9" y2="15" stroke="#ef4444" stroke-width="2"/>
            <line x1="9" y1="9" x2="15" y2="15" stroke="#ef4444" stroke-width="2"/>
          </svg>
          配置错误
        </div>
        <button class="close-btn" @click="showAiErrorModal = false">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
        </button>
      </div>
      <div class="modal-content">
        <p class="error-message">
          AI模型名称错误或KEY不正确，请重新检查核对
        </p>
        <p class="error-submessage">
          请前往设置页面检查您的AI配置信息
        </p>
      </div>
      <div class="modal-actions">
        <button class="cancel-btn" @click="showAiErrorModal = false">
          稍后处理
        </button>
        <button class="confirm-btn" @click="goToSettings">
          前往设置
        </button>
      </div>
    </div>
  </div>

  <!-- 重复任务时间错误提示模态框 -->
  <div v-if="showRepeatTaskTimeError" class="modal-overlay">
    <div class="repeat-task-error-modal" @click.stop>
      <div class="modal-header">
        <div class="modal-title">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" class="warning-icon">
            <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" stroke="#f59e0b" stroke-width="2" fill="none"/>
            <line x1="12" y1="9" x2="12" y2="13" stroke="#f59e0b" stroke-width="2"/>
            <circle cx="12" cy="17" r="1" fill="#f59e0b"/>
          </svg>
          重复任务时间提醒
        </div>
        <button class="close-btn" @click="closeRepeatTaskTimeError">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
        </button>
      </div>
      <div class="modal-content">
        <div class="error-info">
          <p class="error-message">
            不能在任务开始时间之前完成重复任务
          </p>
          <div class="task-info">
            <p><strong>任务名称：</strong>{{ repeatTaskTimeErrorData.taskTitle }}</p>
            <p><strong>任务开始时间：</strong>{{ repeatTaskTimeErrorData.startDate }}</p>
            <p><strong>当前时间：</strong>{{ repeatTaskTimeErrorData.currentDate }}</p>
          </div>
          <p class="error-submessage">
            请等到任务开始时间后再标记为完成，或者修改任务的开始时间。
          </p>
        </div>
      </div>
      <div class="modal-actions">
        <button class="confirm-btn" @click="closeRepeatTaskTimeError">
          我知道了
        </button>
      </div>
    </div>
  </div>

  <!-- 重复任务完成状态错误提示模态框 -->
  <div v-if="showRepeatTaskCompleteError" class="modal-overlay">
    <div class="repeat-task-error-modal" @click.stop>
      <div class="modal-header">
        <div class="modal-title">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" class="error-icon">
            <circle cx="12" cy="12" r="10" stroke="#ef4444" stroke-width="2" fill="none"/>
            <line x1="15" y1="9" x2="9" y2="15" stroke="#ef4444" stroke-width="2"/>
            <line x1="9" y1="9" x2="15" y2="15" stroke="#ef4444" stroke-width="2"/>
          </svg>
          重复任务状态提醒
        </div>
        <button class="close-btn" @click="closeRepeatTaskCompleteError">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
        </button>
      </div>
      <div class="modal-content">
        <div class="error-info">
          <p class="error-message">
            {{ repeatTaskCompleteErrorData.message }}
          </p>
          <div class="task-info">
            <p><strong>任务名称：</strong>{{ repeatTaskCompleteErrorData.taskTitle }}</p>
          </div>
          <p class="error-submessage">
            重复任务一旦完成就会自动创建下一个任务，因此不能取消完成状态。如需修改，请直接编辑新创建的任务。
          </p>
        </div>
      </div>
      <div class="modal-actions">
        <button class="confirm-btn" @click="closeRepeatTaskCompleteError">
          我知道了
        </button>
      </div>
    </div>
  </div>

  <!-- 浮动添加按钮 -->
  <div class="floating-add-btn" @click="openAddTaskModal">
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
      <line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" stroke-width="2"/>
      <line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" stroke-width="2"/>
    </svg>
  </div>

  <!-- 添加任务Modal -->
  <div v-if="showAddTaskModal" class="modal-overlay">
    <div class="add-task-modal" @click.stop>
      <div class="modal-header">
        <h3>添加任务</h3>
        <button class="modal-close" @click="closeAddTaskModal">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
            <line x1="18" y1="6" x2="6" y2="18" stroke="currentColor" stroke-width="2"/>
            <line x1="6" y1="6" x2="18" y2="18" stroke="currentColor" stroke-width="2"/>
          </svg>
        </button>
      </div>
      
      <!-- 重复功能提示 -->
      <div v-if="showRepeatTip" class="repeat-tip">
        <div class="tip-content">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" class="tip-icon">
            <polyline points="23,4 23,10 17,10" stroke="currentColor" stroke-width="2"/>
            <polyline points="1,20 1,14 7,14" stroke="currentColor" stroke-width="2"/>
            <path d="M20.49,9A9,9,0,0,0,5.64,5.64L1,10m22,4L18.36,18.36A9,9,0,0,1,3.51,15" stroke="currentColor" stroke-width="2"/>
          </svg>
          <span>重复任务：每日/每周/每月自动创建相同任务，完成后自动生成下一个</span>
        </div>
        <button class="tip-close" @click="showRepeatTip = false">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <line x1="18" y1="6" x2="6" y2="18" stroke="currentColor" stroke-width="2"/>
            <line x1="6" y1="6" x2="18" y2="18" stroke="currentColor" stroke-width="2"/>
          </svg>
        </button>
      </div>
      
      <!-- Tab切换 -->
      <div class="modal-tabs">
        <button 
          class="tab-btn" 
          :class="{ active: activeTab === 'normal' }"
          @click="activeTab = 'normal'"
        >
          快速添加
        </button>
        <button 
          class="tab-btn" 
          :class="{ active: activeTab === 'smart' }"
          @click="activeTab = 'smart'"
        >
          AI规划
        </button>
      </div>

      <!-- 常规方式内容 -->
      <div v-if="activeTab === 'normal'" class="modal-content">
        <div class="add-task-wrapper">
          <div class="add-task-input">
            <svg class="add-icon" width="16" height="16" viewBox="0 0 24 24" fill="none">
              <line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" stroke-width="2"/>
              <line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" stroke-width="2"/>
            </svg>
            <input
              v-model="newTask"
              type="text"
              placeholder="添加新任务，按回车键确认"
              @keyup.enter="handleAddTask"
            />
          </div>
        </div>

        <!-- 任务选项 -->
        <div class="task-options">
          <div class="option-row">
            <div class="option-group">
              <label>优先级</label>
              <select v-model="newTaskPriority">
                <option value="medium">中等</option>
                <option value="high">高</option>
                <option value="low">低</option>
              </select>
            </div>

            <div class="option-group">
              <label>番茄钟</label>
              <select v-model="newTaskPomodoro">
                <option value="0">不设置</option>
                <option value="1">1个</option>
                <option value="2">2个</option>
                <option value="3">3个</option>
                <option value="4">4个</option>
                <option value="5">5个</option>
              </select>
            </div>

            <div class="option-group">
              <label>
                重复
                <button 
                  type="button" 
                  class="repeat-help-btn" 
                  @click="showRepeatTip = true"
                  title="了解重复功能"
                >
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                    <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                    <path d="M9,9h0a3,3,0,0,1,6,0c0,2-3,3-3,3" stroke="currentColor" stroke-width="2"/>
                    <line x1="12" y1="17" x2="12.01" y2="17" stroke="currentColor" stroke-width="2"/>
                  </svg>
                </button>
              </label>
              <select v-model="newTaskRepeat">
                <option value="none">不重复</option>
                <option value="daily">每日</option>
                <option value="weekly">每周</option>
                <option value="monthly">每月</option>
              </select>
            </div>

            <div class="option-group">
              <label>开始时间</label>
              <input v-model="newTaskStartTime" type="datetime-local" />
            </div>

            <div class="option-group">
              <label>到期时间</label>
              <input v-model="newTaskDueDate" type="datetime-local" />
            </div>
          </div>
        </div>
      </div>

      <!-- 智能方式内容 -->
      <div v-if="activeTab === 'smart'" class="modal-content">
        <!-- 随机建议 -->
        <div class="suggestions-section">
          <h4>快速选择</h4>
          <div class="suggestion-buttons">
            <button
              v-for="suggestion in suggestions"
              :key="suggestion.id"
              class="suggestion-btn"
              :class="{ active: selectedSuggestion === suggestion.id }"
              @click="selectSuggestion(suggestion)"
            >
              <span>{{ suggestion.title }}</span>
            </button>
          </div>
        </div>

        <!-- 自定义输入 -->
        <div class="input-section">
          <textarea
            v-model="customInput"
            placeholder="请描述您想要规划的事情，比如：我想在一个月内减肥10斤"
            rows="3"
            class="custom-input"
          ></textarea>
        </div>

        <!-- 清单选项 -->
        <div class="list-options-section">
          <div class="option-item">
            <label class="switch-label">
              <input
                type="checkbox"
                v-model="createNewList"
                class="switch-input"
              />
              <span class="switch-slider"></span>
              <span class="switch-text">创建新的任务清单</span>
            </label>
            <p class="option-description">
              开启后，智能清单生成的任务将添加到一个新建的清单中，清单名称由AI自动生成
            </p>
          </div>
        </div>

        <!-- 功能说明 -->
        <div class="explanation-section">
          <div class="explanation-card">
            <svg class="info-icon" width="16" height="16" viewBox="0 0 24 24" fill="none">
              <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
              <line x1="12" y1="16" x2="12" y2="12" stroke="currentColor" stroke-width="2"/>
              <line x1="12" y1="8" x2="12.01" y2="8" stroke="currentColor" stroke-width="2"/>
            </svg>
            <div class="explanation-text">
              <p><strong>智能清单功能说明：</strong></p>
              <p>
                基于AI智能分析，为您的目标自动生成详细的任务清单和时间安排，让复杂的计划变得简单易行。
              </p>
            </div>
          </div>
        </div>
      </div>

      <!-- Modal Footer -->
      <div class="modal-footer">
        <button class="btn btn-secondary" @click="closeAddTaskModal">
          取消
        </button>
        <button
          v-if="activeTab === 'normal'"
          class="btn btn-primary"
          @click="confirmAddTask"
          :disabled="!newTask.trim()"
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" stroke-width="2"/>
            <line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" stroke-width="2"/>
          </svg>
          添加
        </button>
        <button
          v-if="activeTab === 'smart'"
          class="btn btn-primary magic-generate-btn"
          @click="generateMagicPlan"
          :disabled="isGenerating || (!selectedSuggestion && !customInput.trim())"
        >
          <svg v-if="isGenerating" class="loading-icon" width="14" height="14" viewBox="0 0 24 24" fill="none">
            <defs>
              <linearGradient id="loadingGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color: #667eea; stop-opacity: 1" />
                <stop offset="100%" style="stop-color: #764ba2; stop-opacity: 1" />
              </linearGradient>
            </defs>
            <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" opacity="0.2"/>
            <path d="M12 2a10 10 0 0 1 10 10" stroke="url(#loadingGradient)" stroke-width="2.5" stroke-linecap="round">
              <animateTransform attributeName="transform" type="rotate" dur="1s" repeatCount="indefinite" values="0 12 12;360 12 12"/>
            </path>
          </svg>
          <svg v-else class="magic-wand" width="25" height="25" viewBox="0 0 24 24" fill="none">
            <defs>
              <linearGradient id="wandGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color: #667eea; stop-opacity: 1" />
                <stop offset="100%" style="stop-color: #764ba2; stop-opacity: 1" />
              </linearGradient>
              <linearGradient id="wandStarGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color: #ffecd2; stop-opacity: 1" />
                <stop offset="100%" style="stop-color: #fcb69f; stop-opacity: 1" />
              </linearGradient>
            </defs>
            <path d="M4 20L20 4" stroke="url(#wandGradient)" stroke-width="2" stroke-linecap="round"/>
            <g transform="translate(18, 6)">
              <path d="M0,-2 L0.6,-0.6 L2,0 L0.6,0.6 L0,2 L-0.6,0.6 L-2,0 L-0.6,-0.6 Z" fill="url(#wandStarGradient)"/>
            </g>
          </svg>
          {{ isGenerating ? "生成中..." : "开始生成" }}
        </button>
      </div>
    </div>
  </div>

  <!-- 番茄钟组件 -->
  <PomodoroTimer ref="pomodoroTimerRef" />
</template>

<script setup>
import { ref, computed, nextTick, watch, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { useTodoStore } from "../../stores/todoStore";
import { useAuthStore } from "../../stores/authStore";
import PomodoroTimer from "./PomodoroTimer.vue";
import { getAiConfig, validateAiConfig } from "@/utils/aiConfig.js";

const {
  state,
  addTask,
  updateTask,
  toggleTaskCompleted: storeToggleTaskCompleted,
  deleteTask,
  abandonTask,
  restoreTask,
  startTask: originalStartTask,
  moveTaskToList,
  createList,
  setCurrentList,
  currentTasks: storeCurrentTasks,
  allLists,
} = useTodoStore();
const authStore = useAuthStore();
const router = useRouter();

// 番茄钟组件引用
const pomodoroTimerRef = ref(null);

// AI配置提示相关
const showAiConfigPrompt = ref(false);

// AI错误提示模态框
const showAiErrorModal = ref(false);

// 重写startTask方法以集成番茄钟
const startTask = (taskId) => {
  // 调用原始的startTask方法更新任务状态
  console.log('taskId', taskId);
  
  originalStartTask(taskId);

  // 获取任务信息
  const task = state.tasks.find((t) => t.id === taskId);
  if (task && pomodoroTimerRef.value) {
    // 启动番茄钟计时器
    pomodoroTimerRef.value.startTaskTimer(task);
  }
};

// 包装toggleTaskCompleted方法以处理复选框状态
const toggleTaskCompleted = (taskId, event) => {
  const result = storeToggleTaskCompleted(taskId);
  
  // 如果store方法返回false，说明操作被阻止，需要恢复复选框状态
  if (result === false && event && event.target) {
    // 恢复复选框的原始状态
    event.target.checked = !event.target.checked;
  }
  
  return result;
};


const newTask = ref("");
const newTaskPriority = ref("medium");
const newTaskPomodoro = ref("0");
const newTaskStartTime = ref("");
const newTaskDueDate = ref("");
const newTaskRepeat = ref("none");

// 设置默认开始时间
const setDefaultStartTime = () => {
  const now = new Date();
  let targetDate = new Date(now);
  
  // 根据当前选中的视图设置不同的默认时间
  if (state.currentView === 'today') {
    // 今天视图：使用当前时间
    targetDate = new Date(now);
  } else if (state.currentView === 'tomorrow') {
    // 明天视图：明天8点
    targetDate = new Date(now);
    targetDate.setDate(now.getDate() + 1);
    targetDate.setHours(8, 0, 0, 0);
  } else {
    // 其他情况：使用当前时间
    targetDate = new Date(now);
  }
  
  const year = targetDate.getFullYear();
  const month = String(targetDate.getMonth() + 1).padStart(2, '0');
  const day = String(targetDate.getDate()).padStart(2, '0');
  const hours = String(targetDate.getHours()).padStart(2, '0');
  const minutes = String(targetDate.getMinutes()).padStart(2, '0');
  newTaskStartTime.value = `${year}-${month}-${day}T${hours}:${minutes}`;
};

// 初始化默认开始时间
setDefaultStartTime();

// 监听视图变化，自动更新默认开始时间
watch(() => state.currentView, () => {
  setDefaultStartTime();
});

const editingTaskId = ref(null);
const editingTaskTitle = ref("");
const showDeleteConfirm = ref(false);
const taskToDelete = ref(null);
const showAbandonConfirm = ref(false);
const taskToAbandon = ref(null);
const showRestoreConfirm = ref(false);
const taskToRestore = ref(null);
const showTimeValidationError = ref(false);
const showTaskDetail = ref(false);
const selectedTask = ref(null);

// 时间验证计算属性
const isTimeInvalid = computed(() => {
  if (!selectedTask.value || !selectedTask.value.startTime || !selectedTask.value.dueDate) {
    return false;
  }
  
  const startTime = new Date(selectedTask.value.startTime);
  const dueDate = new Date(selectedTask.value.dueDate);
  
  return startTime >= dueDate;
});

// 游客模式限制弹窗
const showGuestLimitModal = ref(false);

// 重复功能说明模态框
const showRepeatHelpModal = ref(false);

// 重复功能提示
const showRepeatTip = ref(false);

// 重复任务时间错误提示模态框
const showRepeatTaskTimeError = ref(false);
const repeatTaskTimeErrorData = ref({});

// 重复任务完成状态错误提示模态框
const showRepeatTaskCompleteError = ref(false);
const repeatTaskCompleteErrorData = ref({});

// 添加任务Modal相关
const showAddTaskModal = ref(false);
const activeTab = ref('normal'); // 'normal' 或 'smart'

// 魔法规划相关
const showMagicPlanningModal = ref(false);
const selectedSuggestion = ref(null);
const customInput = ref("");
const selectedTimeframe = ref("1week");
const isGenerating = ref(false);
const createNewList = ref(true); // 是否创建新清单的开关

// 建议选项
const suggestions = ref([
  { 
    id: "fitness", 
    title: "快速规划减肥", 
    prompt: "请帮我制定一个一个月内减重10斤的详细计划，包括饮食建议、运动安排和每周目标" 
  },
  { 
    id: "study", 
    title: "学习计划", 
    prompt: "请帮我制定一个为期3个月的Java编程学习计划，包括知识点、练习项目和阶段目标" 
  },
  { 
    id: "exam", 
    title: "考研任务清单", 
    prompt: "请帮我制定一个6个月的考研复习计划，包括各科目的学习进度、复习重点和模拟考试安排" 
  },
  { 
    id: "work", 
    title: "工作效率提升", 
    prompt: "请帮我制定一个为期2周的工作效率提升计划，包括时间管理、任务优先级和专注力训练" 
  },
  { 
    id: "skill", 
    title: "技能学习", 
    prompt: "请帮我制定一个3个月内掌握摄影技巧的学习计划，包括器材使用、构图技巧和后期处理" 
  },
  { 
    id: "habit", 
    title: "习惯养成", 
    prompt: "请帮我制定一个21天的早起习惯养成计划，包括睡眠规律、晨间仪式和每日任务" 
  },
]);

// 时间段选项
const timeframes = ref([
  { value: "1day", label: "1天" },
  { value: "1week", label: "1周" },
  { value: "1month", label: "1个月" },
  { value: "3months", label: "3个月" },
  { value: "6months", label: "6个月" },
]);

// 搜索相关
const searchQuery = ref("");

// 排序筛选相关
const sortBy = ref("default");
const sortDirection = ref("desc");
const showFilterPanel = ref(false);
const filters = ref({
  showCompleted: true,
  showPending: true,
  priorities: {
    high: true,
    medium: true,
    low: true,
    none: true
  },
  dateRange: {
    start: '',
    end: ''
  }
});

// 批量操作相关
const selectedTasks = ref([]);
const batchTargetListId = ref("");
const showBatchDeleteConfirm = ref(false);

// 计算当前显示的任务列表
const currentTasks = computed(() => {
  let tasks = storeCurrentTasks.value;

  // 如果选择了特定清单，优先按清单过滤（显示清单内所有任务包括已完成的）
  if (
    state.currentListId &&
    ![
      "today",
      "tomorrow",
      "thisweek",
      "planned",
      "high",
      "medium",
      "low",
      "completed",
    ].includes(state.currentView)
  ) {
    tasks = tasks.filter((task) => task.listId === state.currentListId);
    // 清单视图显示所有任务，不过滤已完成任务
  } else if (
    state.currentView === "inbox" ||
    (!state.currentView && !state.currentListId)
  ) {
    // 收件箱视图显示无清单的任务
    tasks = tasks.filter((task) => !task.listId || task.listId === "");
    // 收件箱默认不显示已完成任务
    tasks = tasks.filter((task) => !task.completed);
  } else {
    // 根据当前视图过滤任务
    if (state.currentView === "today") {
      const today = new Date().toDateString();
      tasks = tasks.filter((task) => {
        // 检查开始时间或到期时间是否在今天
        if (task.startTime) {
          const startDate = new Date(task.startTime).toDateString();
          if (startDate === today) return true;
        }
        if (task.dueDate) {
          const dueDate = new Date(task.dueDate).toDateString();
          if (dueDate === today) return true;
        }
        return false;
      });
    } else if (state.currentView === "tomorrow") {
      const tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);
      const tomorrowStr = tomorrow.toDateString();
      tasks = tasks.filter((task) => {
        // 检查开始时间或到期时间是否在明天
        if (task.startTime) {
          const startDate = new Date(task.startTime).toDateString();
          if (startDate === tomorrowStr) return true;
        }
        if (task.dueDate) {
          const dueDate = new Date(task.dueDate).toDateString();
          if (dueDate === tomorrowStr) return true;
        }
        return false;
      });
    } else if (state.currentView === "thisweek") {
      const now = new Date();
      // 计算本周的开始（周一）和结束（周日）
      const dayOfWeek = now.getDay(); // 0=周日, 1=周一, ..., 6=周六
      const daysToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1; // 计算到周一的天数
      const weekStart = new Date(now);
      weekStart.setDate(now.getDate() - daysToMonday);
      weekStart.setHours(0, 0, 0, 0); // 设置为当天开始
      
      const weekEnd = new Date(weekStart);
      weekEnd.setDate(weekStart.getDate() + 6);
      weekEnd.setHours(23, 59, 59, 999); // 设置为当天结束
      
      tasks = tasks.filter((task) => {
        // 检查开始时间或到期时间是否在本周内
        if (task.startTime) {
          const startDate = new Date(task.startTime);
          if (startDate >= weekStart && startDate <= weekEnd) return true;
        }
        if (task.dueDate) {
          const dueDate = new Date(task.dueDate);
          if (dueDate >= weekStart && dueDate <= weekEnd) return true;
        }
        return false;
      });
    } else if (state.currentView === "planned") {
      // 所有任务视图：显示所有未删除的任务，不区分时间、清单归属
      // 这里不需要额外过滤，因为tasks已经是未删除的任务
      // tasks = tasks; // 保持所有任务
    } else if (state.currentView === "high") {
      tasks = tasks.filter((task) => task.priority === "high");
    } else if (state.currentView === "medium") {
      tasks = tasks.filter((task) => task.priority === "medium");
    } else if (state.currentView === "low") {
      tasks = tasks.filter((task) => task.priority === "low");
    } else if (state.currentView === "completed") {
      tasks = tasks.filter((task) => task.completed);
    }

    // 视图模式下默认过滤掉已完成任务（除非在已完成视图或所有任务视图中）
    if (state.currentView !== "completed" && state.currentView !== "planned") {
      tasks = tasks.filter((task) => !task.completed);
    }
  }

  return tasks.sort((a, b) => {
    // 首先按开始时间排序，距离当前时间越近排序越靠前
    const now = new Date();
    const aStartTime = a.startTime ? new Date(a.startTime) : new Date(a.createdAt);
    const bStartTime = b.startTime ? new Date(b.startTime) : new Date(b.createdAt);
    
    // 计算与当前时间的距离（绝对值）
    const aDistance = Math.abs(now - aStartTime);
    const bDistance = Math.abs(now - bStartTime);
    
    if (aDistance !== bDistance) {
      return aDistance - bDistance;
    }
    
    // 如果开始时间距离相同，则按优先级排序
    const priorityOrder = { high: 3, medium: 2, low: 1 };
    if (a.priority !== b.priority) {
      return priorityOrder[b.priority] - priorityOrder[a.priority];
    }
    
    // 最后按创建时间排序
     return new Date(b.createdAt) - new Date(a.createdAt);
   });
});

// 搜索过滤后的任务列表
const filteredTasks = computed(() => {
  let tasks = currentTasks.value;

  // 应用筛选条件
  tasks = tasks.filter((task) => {
    // 状态筛选
    if (task.completed && !filters.value.showCompleted) return false;
    if (!task.completed && !filters.value.showPending) return false;

    // 优先级筛选
    const priority = task.priority || 'none';
    if (!filters.value.priorities[priority]) return false;

    // 时间范围筛选
    if (filters.value.dateRange.start || filters.value.dateRange.end) {
      const taskDate = new Date(task.createdAt);
      if (filters.value.dateRange.start) {
        const startDate = new Date(filters.value.dateRange.start);
        if (taskDate < startDate) return false;
      }
      if (filters.value.dateRange.end) {
        const endDate = new Date(filters.value.dateRange.end);
        endDate.setHours(23, 59, 59, 999); // 包含结束日期的整天
        if (taskDate > endDate) return false;
      }
    }

    return true;
  });

  // 应用搜索过滤
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase().trim();
    tasks = tasks.filter((task) => {
      // 搜索任务标题
      if (task.title.toLowerCase().includes(query)) {
        return true;
      }

      // 搜索任务备注
      if (task.notes && task.notes.toLowerCase().includes(query)) {
        return true;
      }

      // 搜索优先级
      if (task.priority && task.priority.toLowerCase().includes(query)) {
        return true;
      }

      // 搜索标签（如果有的话）
      if (task.tags && Array.isArray(task.tags)) {
        return task.tags.some((tag) => tag.toLowerCase().includes(query));
      }

      return false;
    });
  }

  // 应用排序
  if (sortBy.value === 'default') {
    // 使用默认排序逻辑（与currentTasks相同）
    const now = new Date();
    tasks = [...tasks].sort((a, b) => {
      // 首先按完成状态排序，未完成的在前
      if (a.completed !== b.completed) {
        return a.completed ? 1 : -1;
      }
      
      // 如果都是未完成的任务，按开始时间排序
      if (!a.completed && !b.completed) {
        const aStartTime = a.startTime ? new Date(a.startTime) : new Date(a.createdAt);
        const bStartTime = b.startTime ? new Date(b.startTime) : new Date(b.createdAt);
        
        // 计算与当前时间的距离（绝对值）
        const aDistance = Math.abs(now - aStartTime);
        const bDistance = Math.abs(now - bStartTime);
        
        if (aDistance !== bDistance) {
          return aDistance - bDistance;
        }
        
        // 如果开始时间距离相同，则按优先级排序
        const priorityOrder = { high: 3, medium: 2, low: 1 };
        if (a.priority !== b.priority) {
          return priorityOrder[b.priority] - priorityOrder[a.priority];
        }
        
        // 最后按创建时间排序
        return new Date(b.createdAt) - new Date(a.createdAt);
      }
      
      // 如果都是已完成的任务，按完成时间排序
      return new Date(b.completedAt || b.createdAt) - new Date(a.completedAt || a.createdAt);
    });
  } else {
    // 使用自定义排序
    tasks = [...tasks].sort((a, b) => {
      let aValue, bValue;

      switch (sortBy.value) {
        case 'createTime':
          aValue = new Date(a.createdAt);
          bValue = new Date(b.createdAt);
          break;
        case 'dueDate':
          aValue = a.dueDate ? new Date(a.dueDate) : new Date(0);
          bValue = b.dueDate ? new Date(b.dueDate) : new Date(0);
          break;
        case 'priority':
          const priorityOrder = { high: 3, medium: 2, low: 1, none: 0 };
          aValue = priorityOrder[a.priority || 'none'];
          bValue = priorityOrder[b.priority || 'none'];
          break;
        case 'title':
          aValue = a.title.toLowerCase();
          bValue = b.title.toLowerCase();
          break;
        case 'completed':
          aValue = a.completed ? 1 : 0;
          bValue = b.completed ? 1 : 0;
          break;
        default:
          aValue = new Date(a.createdAt);
          bValue = new Date(b.createdAt);
      }

      if (sortDirection.value === 'asc') {
        return aValue > bValue ? 1 : aValue < bValue ? -1 : 0;
      } else {
        return aValue < bValue ? 1 : aValue > bValue ? -1 : 0;
      }
    });
  }

  return tasks;
});

// 搜索相关方法
const handleSearch = () => {
  // 搜索时清除批量选择
  selectedTasks.value = [];
};

const clearSearch = () => {
  searchQuery.value = "";
  selectedTasks.value = [];
};

// 排序筛选相关计算属性
const hasActiveFilters = computed(() => {
  return !filters.value.showCompleted || 
         !filters.value.showPending ||
         !filters.value.priorities.high ||
         !filters.value.priorities.medium ||
         !filters.value.priorities.low ||
         !filters.value.priorities.none ||
         filters.value.dateRange.start ||
         filters.value.dateRange.end;
});

const activeFilterCount = computed(() => {
  let count = 0;
  if (!filters.value.showCompleted || !filters.value.showPending) count++;
  if (!filters.value.priorities.high || !filters.value.priorities.medium || 
      !filters.value.priorities.low || !filters.value.priorities.none) count++;
  if (filters.value.dateRange.start || filters.value.dateRange.end) count++;
  return count;
});

// 排序筛选方法
const handleSortChange = () => {
  // 排序变化时的处理逻辑
};

const toggleSortDirection = () => {
  sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc';
};

const applyFilters = () => {
  // 应用筛选条件
};

const clearFilters = () => {
  filters.value = {
    showCompleted: true,
    showPending: true,
    priorities: {
      high: true,
      medium: true,
      low: true,
      none: true
    },
    dateRange: {
      start: '',
      end: ''
    }
  };
};

// 获取任务所属清单的颜色
const getTaskListColor = (task) => {
  if (!task.listId) {
    return '#6b7280'; // 默认灰色，用于无清单的任务
  }
  
  const list = state.lists.find(list => list.id === task.listId);
  return list ? list.color : '#6b7280';
};

const handleAddTask = () => {
  if (newTask.value.trim()) {
    addTaskFromForm();
  }
};

const addTaskFromForm = () => {
  if (newTask.value.trim()) {
    // 检查任务数量限制（游客模式限制）
    const taskLimit = authStore.checkTaskLimit(state.tasks.length);
    if (taskLimit.needLogin) {
      // 显示自定义弹窗
      showGuestLimitModal.value = true;
      return;
    }

    const startTime = newTaskStartTime.value || formatDateTimeForDisplay(new Date());
    const dueDate = newTaskDueDate.value || null; // 允许到期时间为空，不设置默认值
    
    // 验证开始时间和到期时间的关系（只有当两个时间都存在且不为空时才验证）
    if (startTime && dueDate && startTime.trim() !== '' && dueDate.trim() !== '') {
      const startTimeObj = new Date(startTime);
      const dueDateObj = new Date(dueDate);
      if (startTimeObj >= dueDateObj) {
        showTimeValidationError.value = true;
        return;
      }
    }

    const options = {
      dueDate: dueDate,
      pomodoroRequired: parseInt(newTaskPomodoro.value) || 0,
      repeatType: newTaskRepeat.value || "none",
      recurrence: newTaskRepeat.value || "none",
      startTime: startTime,
      priority: newTaskPriority.value || "medium",
    };

    // 确定任务应该添加到哪个清单
    let targetListId;
    if (
      state.currentListId &&
      ![
        "today",
        "tomorrow",
        "thisweek",
        "planned",
        "high",
        "medium",
        "low",
        "completed",
        "inbox",
      ].includes(state.currentView)
    ) {
      // 如果当前选中的是具体清单，添加到该清单
      targetListId = state.currentListId;
    } else if (state.currentView === "inbox") {
      // 收件箱视图下创建无清单任务
      targetListId = "";
    } else {
      // 其他视图模式，创建无清单任务（收件箱）
      targetListId = "";
    }

    addTask(newTask.value.trim(), targetListId, options);

    resetTaskForm();

    closeAddTaskModal();
  }
};

const resetTaskForm = () => {
  newTask.value = "";
  newTaskPriority.value = "medium";
  newTaskPomodoro.value = "0";
  newTaskDueDate.value = "";
  newTaskRepeat.value = "none";
  setDefaultStartTime();
};

// 游客模式弹窗处理
const closeGuestLimitModal = () => {
  showGuestLimitModal.value = false;
};

const handleGuestLogin = () => {
  showGuestLimitModal.value = false;
  authStore.showLoginModal();
};

// 添加任务Modal相关方法
const closeAddTaskModal = () => {
  showAddTaskModal.value = false;
  activeTab.value = 'normal';
  resetTaskForm();
  // 重置智能方式相关状态
  selectedSuggestion.value = null;
  customInput.value = "";
  // 移除键盘事件监听器
  document.removeEventListener('keydown', handleKeydown);
};

// 处理键盘事件
const handleKeydown = (event) => {
  if (event.key === 'Escape' && showAddTaskModal.value) {
    closeAddTaskModal();
  }
};

// 打开新建任务模态框
const openAddTaskModal = () => {
  showAddTaskModal.value = true;
  activeTab.value = 'normal';
  resetTaskForm();
  // 添加键盘事件监听器
  document.addEventListener('keydown', handleKeydown);
  // 自动聚焦到输入框
  nextTick(() => {
    const input = document.querySelector('.add-task-modal input[type="text"]');
    if (input) {
      input.focus();
    }
  });
};

// 处理 Electron 菜单新建任务事件
const handleElectronNewTask = () => {
  openAddTaskModal();
};

const confirmAddTask = () => {
  if (activeTab.value === 'normal') {
    addTaskFromForm();
    closeAddTaskModal();
  }
};

// 魔法规划相关方法
const selectSuggestion = (suggestion) => {
  selectedSuggestion.value = suggestion.id;
  customInput.value = suggestion.prompt;
};

const closeMagicPlanningModal = () => {
  showMagicPlanningModal.value = false;
  showAddTaskModal.value = false;
  selectedSuggestion.value = null;
  customInput.value = "";
  // createNewList.value = false; // 保持创建新清单开关状态，不重置
  selectedTimeframe.value = "1week";
  isGenerating.value = false;
};

// 处理智能清单按钮点击
const handleMagicPlanningClick = async () => {
  try {
    // 获取AI配置
    const aiConfig = await getAiConfig();
    console.log('获取到的AI配置:', aiConfig);
    
    // 使用validateAiConfig函数进行严格验证
    const isValid = validateAiConfig(aiConfig);
    console.log('AI配置验证结果:', isValid);
    
    if (!isValid) {
      console.log('AI配置验证失败，详细信息:');
      console.log('apiUrl:', `"${aiConfig.apiUrl}"`);
      console.log('modelName:', `"${aiConfig.modelName}"`);
      console.log('apiKey:', `"${aiConfig.apiKey}"`);
      // 显示友好提示
      showAiConfigPrompt.value = true;
      return;
    }
    
    console.log('AI配置验证成功，打开智能清单弹窗');
    // 配置完整，直接打开智能清单弹窗
    showMagicPlanningModal.value = true;
  } catch (error) {
    console.error('检查AI配置失败:', error);
    // 显示友好提示
    showAiConfigPrompt.value = true;
  }
};

// 跳转到设置页面
const goToSettings = () => {
  showAiConfigPrompt.value = false;
  router.push('/settings');
};

const generateMagicPlan = async () => {
  if (isGenerating.value) return;

  const planContent = customInput.value.trim();
  if (!planContent) return;

  isGenerating.value = true;

  try {
    // 获取AI配置
    const aiConfig = await getAiConfig();

    // 构建提示词
    const currentTime = new Date();
    const currentTimeStr = formatDateTimeForDisplay(currentTime);
    const futureTimeStr = formatDateTimeForDisplay(new Date(currentTime.getTime() + 60*60*1000));
    
    const prompt = `请为以下目标制定详细的任务清单。目标：${planContent}。

重要提醒：
- 当前时间是：${currentTimeStr}
- 所有任务的开始时间必须从当前时间或之后开始
- 请合理安排任务的开始时间和到期时间
- 合理安排任务之间的间隔时间

请严格按照以下JSON格式返回，不要包含任何其他文字说明：
{
  "listName": "清单名称（不超过8个字的中文名称）",
  "tasks": [
    {
      "title": "任务标题",
      "description": "任务描述（可选）",
      "startTime": "年-月-日 时:分:秒",
      "dueDate": "年-月-日 时:分:秒",
      "priority": "medium",
      "pomodoroRequired": 1,
      "day": 1
    }
  ]
}

其中：
- listName: 为这个任务清单生成一个简洁的中文名称（不超过8个字）
- title: 任务标题（必填）
- description: 详细描述任务的内容，给出一些具体可实施的建议，以及需要的时间和资源，不要让用户觉得空洞
- startTime: 任务开始时间，年-月-日 时:分:秒格式，第一个任务必须从当前时间${currentTimeStr}开始或之后，之后的任务合理规划间隔时间
- dueDate: 任务截止时间，年-月-日 时:分:秒格式，必须晚于开始时间
- priority: 正确预估任务的优先级，任务优先级（high/medium/low，默认medium）
- pomodoroRequired: 正确预估任务需要的时间，用番茄钟数量表示（1-5，默认1，只能是整数，1个番茄钟是25分钟）
- day: 第几天执行（1-30），如果是按周规划则用1-7表示第几天
请确保返回的是有效的JSON格式，时间要合理安排。`

    // 调用API（使用用户配置的设置）
    const response = await fetch(
      aiConfig.apiUrl,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${aiConfig.apiKey}`,
        },
        body: JSON.stringify({
          model: aiConfig.modelName,
          messages: [
            {
              role: "user",
              content: prompt,
            },
          ],
        }),
      }
    );

    if (!response.ok) {
      throw new Error(`API请求失败: ${response.status}`);
    }

    const data = await response.json();
    const content = data.choices?.[0]?.message?.content;

    if (content) {
      // 打印API返回的内容
      console.log('魔法规划API返回内容:', content);
      // 解析JSON格式的任务列表和清单名称
      const result = parseJsonTasks(content);
      const { tasks, listName } = result;

      if (tasks.length > 0) {
        // 批量添加任务，传入清单名称
        await addTasksFromMagicPlan(tasks, listName);

        // 关闭弹窗
        closeMagicPlanningModal();

        // 显示成功提示
        // 这里可以添加一个成功提示
        console.log(`成功生成 ${tasks.length} 个任务，清单名称: ${listName}`);
      } else {
        throw new Error("未能解析出有效的任务列表");
      }
    } else {
      throw new Error("API返回内容为空");
    }
  } catch (error) {
    console.error("魔法规划生成失败:", error);
    // 显示错误提示模态框
    showAiErrorModal.value = true;
  } finally {
    isGenerating.value = false;
  }
};

// 解析JSON格式的任务列表
const parseJsonTasks = (content) => {
  // 预处理内容，移除可能的干扰字符
  let cleanContent = content.trim();
  
  // 移除可能的markdown代码块标记
  cleanContent = cleanContent.replace(/^```json\s*/, '').replace(/\s*```$/, '');
  cleanContent = cleanContent.replace(/^```\s*/, '').replace(/\s*```$/, '');
  
  try {
    // 尝试直接解析JSON
    const jsonData = JSON.parse(cleanContent);
    if (jsonData.tasks && Array.isArray(jsonData.tasks)) {
      const tasks = jsonData.tasks.filter(task => task.title && task.title.trim());
      return {
        tasks: tasks,
        listName: jsonData.listName || '魔法规划清单'
      };
    }
  } catch (error) {
    console.warn('JSON解析失败，尝试提取JSON部分:', error);
    
    // 尝试多种方式提取JSON
    const jsonPatterns = [
      /\{[\s\S]*\}/,  // 匹配整个JSON对象
      /\{[\s\S]*?"tasks"[\s\S]*?\}/,  // 匹配包含tasks的JSON
      /\{[\s\S]*?"listName"[\s\S]*?\}/  // 匹配包含listName的JSON
    ];
    
    for (const pattern of jsonPatterns) {
      const jsonMatch = cleanContent.match(pattern);
      if (jsonMatch) {
        try {
          let jsonStr = jsonMatch[0];
          
          // 尝试修复常见的JSON格式问题
          jsonStr = jsonStr.replace(/,\s*}/g, '}');  // 移除尾随逗号
          jsonStr = jsonStr.replace(/,\s*]/g, ']');   // 移除数组尾随逗号
          
          const jsonData = JSON.parse(jsonStr);
          if (jsonData.tasks && Array.isArray(jsonData.tasks)) {
            const tasks = jsonData.tasks.filter(task => task.title && task.title.trim());
            return {
              tasks: tasks,
              listName: jsonData.listName || '魔法规划清单'
            };
          }
        } catch (innerError) {
          console.warn(`JSON模式 ${pattern} 解析失败:`, innerError);
          continue;
        }
      }
    }
    
    // 如果所有JSON解析都失败，尝试逐行解析
    try {
      const lines = cleanContent.split('\n');
      let jsonStart = -1;
      let jsonEnd = -1;
      let braceCount = 0;
      
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();
        if (line.includes('{')) {
          if (jsonStart === -1) jsonStart = i;
          braceCount += (line.match(/\{/g) || []).length;
        }
        if (line.includes('}')) {
          braceCount -= (line.match(/\}/g) || []).length;
          if (braceCount === 0 && jsonStart !== -1) {
            jsonEnd = i;
            break;
          }
        }
      }
      
      if (jsonStart !== -1 && jsonEnd !== -1) {
        const jsonLines = lines.slice(jsonStart, jsonEnd + 1);
        const jsonStr = jsonLines.join('\n');
        const jsonData = JSON.parse(jsonStr);
        
        if (jsonData.tasks && Array.isArray(jsonData.tasks)) {
          const tasks = jsonData.tasks.filter(task => task.title && task.title.trim());
          return {
            tasks: tasks,
            listName: jsonData.listName || '魔法规划清单'
          };
        }
      }
    } catch (lineError) {
      console.warn('逐行解析也失败:', lineError);
    }
    
    // 如果JSON解析都失败，回退到markdown解析
    console.warn('回退到markdown解析模式');
    const fallbackTasks = parseMarkdownTasksFallback(cleanContent);
    return {
      tasks: fallbackTasks,
      listName: '魔法规划清单'
    };
  }
  
  return {
    tasks: [],
    listName: '魔法规划清单'
  };
};

// 回退的markdown解析方法
const parseMarkdownTasksFallback = (content) => {
  const lines = content.split("\n");
  const tasks = [];

  for (const line of lines) {
    const trimmed = line.trim();
    // 匹配markdown列表格式：- 任务名称 或 * 任务名称
    const match = trimmed.match(/^[-*]\s+(.+)$/);
    if (match && match[1]) {
      const taskTitle = match[1].trim();
      if (taskTitle) {
        tasks.push({ title: taskTitle, description: '', day: 1 });
      }
    }
  }

  return tasks;
};

// 批量添加任务
const addTasksFromMagicPlan = async (tasks, listName = '魔法规划清单') => {
  let targetListId = state.currentListId || "";
  
  // 如果开启了创建新清单选项
  if (createNewList.value && tasks.length > 0) {
    try {
      // 生成随机颜色
      const colors = [
        '#6366f1', '#ef4444', '#f59e0b', '#10b981', 
        '#8b5cf6', '#f97316', '#06b6d4', '#84cc16'
      ];
      const randomColor = colors[Math.floor(Math.random() * colors.length)];
      
      // 使用从API返回的清单名称
      const finalListName = listName || '魔法规划清单';
      
      // 创建新清单
      const newList = createList(finalListName, randomColor);
      targetListId = newList.id;
      
      // 切换到新创建的清单
      setCurrentList(targetListId);
      
      console.log('创建新清单:', finalListName, '颜色:', randomColor);
    } catch (error) {
      console.error('创建清单失败:', error);
      // 如果创建失败，使用当前清单
      targetListId = state.currentListId || "";
    }
  }
  
  for (const task of tasks) {
    // 处理开始时间和到期时间
    let dueDate = "";
    let startTime = "";
    let dueDateISO = "";
    
    // 优先使用API返回的时间，并进行时间验证
    const currentTime = new Date();
    
    if (task.startTime) {
      try {
        const startDate = new Date(task.startTime);
        // 验证开始时间是否合理（不能早于当前时间太多）
        if (startDate < new Date(currentTime.getTime() - 24*60*60*1000)) {
          console.warn('API返回的开始时间过早，使用当前时间:', task.startTime);
          startTime = formatDateTimeForDisplay(currentTime);
        } else {
          startTime = formatDateTimeForDisplay(startDate);
        }
      } catch (error) {
        console.warn('解析startTime失败:', error);
        startTime = formatDateTimeForDisplay(currentTime);
      }
    }
    
    if (task.dueDate) {
      try {
        const dueDateObj = new Date(task.dueDate);
        
        // 验证截止时间是否晚于开始时间
        if (startTime) {
          const startTimeObj = new Date(startTime.replace(' ', 'T'));
          if (dueDateObj <= startTimeObj) {
            console.warn('API返回的截止时间不合理，调整为开始时间后2小时');
            // 调整截止时间为开始时间后2小时，确保有足够的时间间隔
            const adjustedDueDate = new Date(startTimeObj.getTime() + 2*60*60*1000);
            dueDateISO = formatDateTimeForDisplay(adjustedDueDate);
            dueDate = formatDateTimeForDisplay(adjustedDueDate).split(' ')[0];
          } else {
            dueDateISO = formatDateTimeForDisplay(dueDateObj);
            dueDate = formatDateTimeForDisplay(dueDateObj).split(' ')[0];
          }
        } else {
          dueDateISO = formatDateTimeForDisplay(dueDateObj);
          dueDate = formatDateTimeForDisplay(dueDateObj).split(' ')[0];
        }
      } catch (error) {
        console.warn('解析dueDate失败:', error);
      }
    }
    
    // 不再自动设置默认到期时间，允许任务没有到期时间
    // if (!dueDate) {
    //   // 如果没有具体时间，根据day字段计算
    //   const now = new Date();
    //   if (task.day && typeof task.day === 'number') {
    //     now.setDate(now.getDate() + task.day - 1); // day从1开始，所以减1
    //   } else {
    //     // 使用默认的时间范围
    //     switch (selectedTimeframe.value) {
    //       case "1week":
    //         now.setDate(now.getDate() + 7);
    //         break;
    //       case "1month":
    //         now.setMonth(now.getMonth() + 1);
    //         break;
    //       case "3months":
    //         now.setMonth(now.getMonth() + 3);
    //         break;
    //       case "6months":
    //         now.setMonth(now.getMonth() + 6);
    //         break;
    //     }
    //   }
    //   dueDate = formatDateTimeForDisplay(now).split(' ')[0];
    // }

    // 构建任务备注
    let notes = task.description || "";

    // 如果还没有设置开始时间，使用当前时间作为默认值
    if (!startTime) {
      startTime = formatDateTimeForDisplay(new Date());
    }

    // 最终验证：只有当开始时间和到期时间都存在且不为空时才验证
    if (startTime && (dueDateISO || dueDate) && 
        startTime.trim() !== '' && (dueDateISO || dueDate).trim() !== '') {
      const finalStartTime = new Date(startTime);
      const finalDueDate = new Date(dueDateISO || dueDate);
      if (finalStartTime >= finalDueDate) {
        console.warn(`任务 "${task.title}" 的时间设置不合理，跳过创建`);
        continue; // 跳过这个任务的创建
      }
    }

    // 构建任务选项
    const taskOptions = {
      priority: task.priority || "medium",
      dueDate: dueDateISO || dueDate,
      startTime: startTime,
      notes: notes,
      pomodoroRequired: task.pomodoroRequired || 1,
      repeatType: "none"
    };

    // 正确调用addTask方法：第一个参数是任务文本，第二个是listId，第三个是选项
    const newTask = addTask(
      task.title, 
      targetListId, 
      taskOptions
    );
    
    console.log('添加任务:', newTask);
  }
};



const saveTaskEdit = () => {
  if (editingTaskTitle.value.trim() && editingTaskId.value) {
    updateTask(editingTaskId.value, { title: editingTaskTitle.value.trim() });
  }
  editingTaskId.value = null;
  editingTaskTitle.value = "";
};

const cancelTaskEdit = () => {
  editingTaskId.value = null;
  editingTaskTitle.value = "";
};

const confirmDeleteTask = (task) => {
  taskToDelete.value = task;
  showDeleteConfirm.value = true;
};

const confirmAbandonTask = (task) => {
  taskToAbandon.value = task;
  showAbandonConfirm.value = true;
};

const handleDeleteTask = () => {
  if (taskToDelete.value) {
    deleteTask(taskToDelete.value.id);
  }
  showDeleteConfirm.value = false;
  taskToDelete.value = null;
};

const handleAbandonTask = () => {
  if (taskToAbandon.value) {
    abandonTask(taskToAbandon.value.id);
  }
  showAbandonConfirm.value = false;
  taskToAbandon.value = null;
};

const cancelDeleteTask = () => {
  showDeleteConfirm.value = false;
  taskToDelete.value = null;
};

const cancelAbandonTask = () => {
  showAbandonConfirm.value = false;
  taskToAbandon.value = null;
};

const confirmRestoreTask = (task) => {
  taskToRestore.value = task;
  showRestoreConfirm.value = true;
};

const handleRestoreTask = () => {
  if (taskToRestore.value) {
    restoreTask(taskToRestore.value.id);
  }
  showRestoreConfirm.value = false;
  taskToRestore.value = null;
};

const cancelRestoreTask = () => {
  showRestoreConfirm.value = false;
  taskToRestore.value = null;
};

const closeTimeValidationError = () => {
  showTimeValidationError.value = false;
};

const openTaskDetail = (task) => {
  selectedTask.value = { 
    ...task,
    recurrence: task.recurrence || task.repeatType || 'none', // 确保 recurrence 字段有默认值
    listId: task.listId || '' // 确保 listId 字段有默认值，空字符串对应"无清单"
  };
  showTaskDetail.value = true;
};

const closeTaskDetail = () => {
  showTaskDetail.value = false;
  selectedTask.value = null;
};

const saveTaskDetail = () => {
  if (selectedTask.value) {
    // 验证开始时间和到期时间的关系（只有当两个时间都存在且不为空时才验证）
    if (selectedTask.value.startTime && selectedTask.value.dueDate && 
        selectedTask.value.startTime.trim() !== '' && selectedTask.value.dueDate.trim() !== '') {
      const startTime = new Date(selectedTask.value.startTime);
      const dueDate = new Date(selectedTask.value.dueDate);
      if (startTime >= dueDate) {
        showTimeValidationError.value = true;
        return;
      }
    }

    // 检查任务是否需要移动到其他清单
    const originalTask = state.tasks.find(
      (task) => task.id === selectedTask.value.id
    );
    if (originalTask && originalTask.listId !== selectedTask.value.listId) {
      // 如果清单发生变化，先移动任务到新清单
      moveTaskToList(selectedTask.value.id, selectedTask.value.listId);
    }

    // 更新任务信息
    updateTask(selectedTask.value.id, selectedTask.value);
    closeTaskDetail();
  }
};

const getPriorityColor = (priority) => {
  switch (priority) {
    case "high":
      return "#ef4444";
    case "medium":
      return "#f59e0b";
    case "low":
      return "#10b981";
    default:
      return "#6b7280";
  }
};

const getPriorityText = (priority) => {
  switch (priority) {
    case "high":
      return "高";
    case "medium":
      return "中";
    case "low":
      return "低";
    default:
      return "无";
  }
};

const getRecurrenceText = (recurrence) => {
  switch (recurrence) {
    case "daily":
      return "每日";
    case "weekly":
      return "每周";
    case "monthly":
      return "每月";
    default:
      return "无";
  }
};

const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleDateString("zh-CN", {
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 格式化时间为年-月-日 时:分:秒格式
const formatDateTimeForDisplay = (dateString) => {
  if (!dateString) return "";
  try {
    const date = new Date(dateString);
    // 转换为本地时间并格式化为年-月-日 时:分:秒格式
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    console.warn('格式化时间失败:', error);
    return "";
  }
};

// 格式化时间为datetime-local输入框格式
const formatDateTimeForInput = (dateString) => {
  if (!dateString) return "";
  try {
    const date = new Date(dateString);
    // 转换为本地时间并格式化为YYYY-MM-DDTHH:mm格式
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day}T${hours}:${minutes}`;
  } catch (error) {
    console.warn('格式化时间失败:', error);
    return "";
  }
};

// 更新任务开始时间
const updateTaskStartTime = (value) => {
  if (selectedTask.value) {
    if (value && value.trim() !== '') {
      try {
        // 将datetime-local格式转换为Date对象，然后转换为年-月-日 时:分:秒格式
        const date = new Date(value);
        selectedTask.value.startTime = formatDateTimeForDisplay(date);
        
        // 实时验证：只有当开始时间和到期时间都存在且不为空时才验证
        if (selectedTask.value.dueDate && selectedTask.value.dueDate.trim() !== '') {
          const startTime = new Date(selectedTask.value.startTime);
          const dueDate = new Date(selectedTask.value.dueDate);
          if (startTime >= dueDate) {
            console.warn('开始时间不能晚于或等于到期时间');
          }
        }
      } catch (error) {
        console.warn('更新开始时间失败:', error);
      }
    } else {
      // 如果value为空，清空开始时间
      selectedTask.value.startTime = null;
    }
  }
};

// 更新任务到期时间
const updateTaskDueDate = (value) => {
  if (selectedTask.value) {
    if (value && value.trim() !== '') {
      try {
        // 将datetime-local格式转换为Date对象，然后转换为年-月-日 时:分:秒格式
        const date = new Date(value);
        selectedTask.value.dueDate = formatDateTimeForDisplay(date);
        
        // 实时验证：只有当开始时间和到期时间都存在且不为空时才验证
        if (selectedTask.value.startTime && selectedTask.value.startTime.trim() !== '') {
          const startTime = new Date(selectedTask.value.startTime);
          const dueDate = new Date(selectedTask.value.dueDate);
          if (startTime >= dueDate) {
            console.warn('到期时间不能早于或等于开始时间');
          }
        }
      } catch (error) {
        console.warn('更新到期时间失败:', error);
      }
    } else {
      // 如果value为空，清空到期时间
      selectedTask.value.dueDate = null;
    }
  }
};

const isOverdue = (dueDate) => {
  if (!dueDate) return false;
  return new Date(dueDate) < new Date();
};

// 批量操作函数
const toggleTaskSelection = (taskId) => {
  const index = selectedTasks.value.indexOf(taskId);
  if (index > -1) {
    selectedTasks.value.splice(index, 1);
  } else {
    selectedTasks.value.push(taskId);
  }
};

const batchMoveToList = () => {
  if (batchTargetListId.value && selectedTasks.value.length > 0) {
    const moveCount = selectedTasks.value.length;
    selectedTasks.value.forEach((taskId) => {
      moveTaskToList(taskId, batchTargetListId.value);
    });
    // 清空选择
    selectedTasks.value = [];
    batchTargetListId.value = "";
    
    // 显示成功提示
    console.log(`成功移动 ${moveCount} 个任务到目标清单`);
  }
};

// 批量删除相关方法
const confirmBatchDelete = () => {
  if (selectedTasks.value.length > 0) {
    showBatchDeleteConfirm.value = true;
  }
};

const cancelBatchDelete = () => {
  showBatchDeleteConfirm.value = false;
};

const handleBatchDelete = () => {
  if (selectedTasks.value.length > 0) {
    const deleteCount = selectedTasks.value.length;
    selectedTasks.value.forEach((taskId) => {
      deleteTask(taskId);
    });
    // 清空选择
    selectedTasks.value = [];
    showBatchDeleteConfirm.value = false;
    
    // 显示成功提示
    console.log(`成功删除 ${deleteCount} 个任务`);
  }
};

// 处理重复任务时间错误事件
const handleRepeatTaskTimeError = (event) => {
  repeatTaskTimeErrorData.value = event.detail;
  showRepeatTaskTimeError.value = true;
};

// 关闭重复任务时间错误模态框
const closeRepeatTaskTimeError = () => {
  showRepeatTaskTimeError.value = false;
  repeatTaskTimeErrorData.value = {};
};

// 处理重复任务完成状态错误事件
const handleRepeatTaskCompleteError = (event) => {
  repeatTaskCompleteErrorData.value = event.detail;
  showRepeatTaskCompleteError.value = true;
};

// 关闭重复任务完成状态错误模态框
const closeRepeatTaskCompleteError = () => {
  showRepeatTaskCompleteError.value = false;
  repeatTaskCompleteErrorData.value = {};
};

// 生命周期钩子
onMounted(() => {
  // 监听重复任务时间错误事件
  window.addEventListener('showRepeatTaskTimeError', handleRepeatTaskTimeError);
  // 监听重复任务完成状态错误事件
  window.addEventListener('showRepeatTaskCompleteError', handleRepeatTaskCompleteError);
  // 监听 Electron 菜单新建任务事件
  window.addEventListener('electron-new-task', handleElectronNewTask);
});

onUnmounted(() => {
  // 移除事件监听器
  window.removeEventListener('showRepeatTaskTimeError', handleRepeatTaskTimeError);
  window.removeEventListener('showRepeatTaskCompleteError', handleRepeatTaskCompleteError);
  window.removeEventListener('electron-new-task', handleElectronNewTask);
});
</script>

<style lang="less" scoped>
.task-list-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: var(--background-color);
  overflow: hidden;

  .batch-operations {
    padding: 15px 20px;
    background-color: var(--surface-color, var(--background-color));
    border-bottom: 1px solid var(--border-color);
    border-radius: 8px;
    margin: 0 20px;
    box-shadow: 0 2px 4px var(--shadow-color, rgba(0, 0, 0, 0.05));

    .batch-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 16px;

      .batch-title {
        font-weight: 600;
        color: var(--text-primary, #495057);
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 8px;
        
        &::before {
          content: '';
          width: 4px;
          height: 16px;
          background: var(--primary-color, #3b82f6);
          border-radius: 2px;
        }
      }

      .batch-actions {
          display: flex;
          align-items: center;
          gap: 12px;
          flex-wrap: wrap;

          @media (max-width: 768px) {
            flex-direction: column;
            align-items: stretch;
            gap: 8px;
          }

          .batch-select {
            padding: 8px 12px;
            border: 1px solid var(--border-color, #d1d5db);
            border-radius: 6px;
            font-size: 14px;
            background: var(--background-color, white);
            color: var(--text-primary, #374151);
            min-width: 140px;
            transition: all 0.2s;

            @media (max-width: 768px) {
              min-width: auto;
              width: 100%;
            }

            &:focus {
              outline: none;
              border-color: var(--primary-color, #3b82f6);
              box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
            }
          }

        .batch-btn {
          padding: 8px 16px;
          font-size: 14px;
          border-radius: 6px;
          font-weight: 500;
          transition: all 0.2s;
          border: none;
          cursor: pointer;
          display: flex;
          align-items: center;
          gap: 6px;
          white-space: nowrap;

          @media (max-width: 768px) {
            justify-content: center;
            width: 100%;
            padding: 10px 16px;
          }

          svg {
            flex-shrink: 0;
            margin-right: 2px;
          }

          &.btn-secondary {
            background: var(--button-secondary-bg, #f3f4f6);
            color: var(--text-primary, #374151);
            border: 1px solid var(--border-color, #d1d5db);

            &:hover:not(:disabled) {
              background: var(--button-secondary-hover, #e5e7eb);
              transform: translateY(-1px);
              box-shadow: 0 2px 4px var(--shadow-color, rgba(0, 0, 0, 0.1));
            }
          }

          &.btn-danger {
            background: #ef4444;
            color: white;

            &:hover:not(:disabled) {
              background: #dc2626;
              transform: translateY(-1px);
              box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
            }
          }

          &:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none !important;
            box-shadow: none !important;
          }

          &:active:not(:disabled) {
            transform: translateY(0);
          }
        }
      }
    }
  }

  .add-task-section {
    padding: 16px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    gap: 12px;
    align-items: flex-end;

    .magic-planning-wrapper {
      flex-shrink: 0;

      .magic-planning-btn {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 10px 16px;
        background: linear-gradient(
          135deg,
          #8b5cf6 0%,
          #06b6d4 50%,
          #10b981 100%
        );
        background-size: 200% 200%;
        border: none;
        border-radius: 12px;
        color: white;
        font-size: 13px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        animation: magicGradient 4s ease infinite;
        box-shadow: 0 4px 12px rgba(139, 92, 246, 0.3), 0 2px 4px rgba(0, 0, 0, 0.1);
        position: relative;
        overflow: hidden;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: -100%;
          width: 100%;
          height: 100%;
          background: linear-gradient(
            90deg,
            transparent,
            rgba(255, 255, 255, 0.2),
            transparent
          );
          transition: left 0.5s ease;
        }

        &:hover {
          transform: translateY(-2px) scale(1.02);
          box-shadow: 0 8px 20px rgba(139, 92, 246, 0.4), 0 4px 8px rgba(0, 0, 0, 0.15);
          animation-duration: 2s;
          
          &::before {
            left: 100%;
          }
        }

        &:active {
          transform: translateY(-1px) scale(1.01);
          transition-duration: 0.1s;
        }

        .magic-icon {
          flex-shrink: 0;
          filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.1));
        }

        span {
          white-space: nowrap;
          text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
          position: relative;
          z-index: 1;
        }
      }
    }

    .add-task-wrapper {
      display: flex;
      flex-grow: 1;
      flex-direction: column;
      gap: 4px;
    }

    .add-task-wrapper label {
      font-size: 12px;
      font-weight: 500;
      color: #64748b;
    }

    .add-task-box {
      display: flex;
      gap: 10px;
      width: 100%;
    }

    .add-task-input {
      display: flex;
      flex-grow: 1;
      align-items: center;
      gap: 12px;
      height: 37px;
      padding: 12px 16px;
      border: 1px solid var(--border-color);
      background-color: var(--background-color);
      border-radius: 8px;
      transition: all 0.2s ease;

      &:focus-within {
        border-color: var(--border-color);
        box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
      }

      .add-icon {
        color: var(--primary-color);
        flex-shrink: 0;
      }

      input {
        flex: 1;
        border: none;
        outline: none;
        background-color: var(--background-color);
        color: var(--text-primary);
        font-size: 14px;

        &::placeholder {
          color: #94a3b8;
        }
      }
    }

    .task-options {
      .option-row {
        display: flex;
        gap: 12px;
        align-items: end;
      }

      .option-group {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 4px;

        &:last-child {
          flex: 0 0 auto;
        }

        &.full-width {
          flex: 1 1 100%;
        }

        label {
          font-size: 12px;
          font-weight: 500;
          display: flex;
          align-items: center;
          gap: 5px;
          color: #64748b;
        }

        select,
        input,
        textarea {
          padding: 8px 10px;
          border: 1px solid #d1d5db;
          border-radius: 6px;
          font-size: 13px;
          box-sizing: border-box;
          background: white;
          transition: border-color 0.2s ease;

          &:focus {
            outline: none;
            border-color: #6366f1;
            box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
          }
        }

        select,
        input {
          height: 37px;
          max-height: 37px;
        }

        textarea {
          min-height: 80px;
          resize: vertical;
          font-family: inherit;
        }
      }

      .add-btn {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 8px 16px;
        font-size: 13px;
        font-weight: 500;
        border-radius: 6px;
        transition: all 0.2s ease;
        background: var(--button-secondary-bg);
        color: var(--text-primary);
        border: 1px solid var(--border-color);
        cursor: pointer;

        &:hover {
          background: var(--primary-color, #2563eb);
          border-color: var(--border-hover);
        }

        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        svg {
          width: 14px;
          height: 14px;
        }
      }
    }
  }

  .task-list {
    flex: 1;
    overflow-y: auto;
    padding: 0 20px 40px 20px;

    .task-item {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      padding: 16px 0;
      border-bottom: 1px solid var(--border-color);
      transition: all 0.2s ease;
      cursor: pointer;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background: rgba(99, 102, 241, 0.02);
        margin: 0 -24px;
        padding-left: 24px;
        padding-right: 24px;
        border-radius: 8px;

        .task-actions {
          opacity: 1;
        }
      }

      &.completed {
        opacity: 0.6;

        .task-title {
          text-decoration: line-through;
        }
      }

      &.overdue {
        .due-date {
          color: #dc2626;
          background-color: #fee2e2;
        }
      }

      &.selected {
        background: #e0e7ff;
        border-left: 3px solid #6366f1;
        margin: 0 -24px;
        padding-left: 21px;
        padding-right: 24px;
        border-radius: 8px;
      }

      .batch-checkbox {
        margin-top: 2px;

        input[type="checkbox"] {
          display: none;
        }

        label {
          display: block;
          width: 18px;
          height: 18px;
          border: 2px solid #f59e0b;
          border-radius: 2px;
          cursor: pointer;
          position: relative;
          transition: all 0.2s ease;
          background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);

          &:hover {
            border-color: #d97706;
            background: linear-gradient(135deg, #fde68a 0%, #fcd34d 100%);
          }

          &::before {
            content: "";
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 8px;
            height: 8px;
            border-radius: 1px;
            background: #f59e0b;
            opacity: 0;
            transition: opacity 0.2s ease;
          }
        }

        input[type="checkbox"]:checked + label {
          background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
          border-color: #d97706;

          &::before {
            opacity: 0;
          }

          &::after {
            content: "";
            position: absolute;
            left: 3px;
            top: 0px;
            width: 6px;
            height: 10px;
            border: solid white;
            border-width: 0 2px 2px 0;
            transform: rotate(45deg);
          }
        }
      }

      .task-checkbox {
        margin-top: 2px;

        input[type="checkbox"] {
          display: none;
        }

        label {
          display: block;
          width: 20px;
          height: 20px;
          border: 2px solid #d1d5db;
          border-radius: 4px;
          cursor: pointer;
          position: relative;
          transition: all 0.2s ease;

          &:hover {
            border-color: #6366f1;
          }

          &::after {
            content: "";
            position: absolute;
            top: 2px;
            left: 6px;
            width: 4px;
            height: 8px;
            border: solid white;
            border-width: 0 2px 2px 0;
            transform: rotate(45deg);
            opacity: 0;
            transition: opacity 0.2s ease;
          }
        }

        input:checked + label {
          background: var(--primary-color);
          border-color: var(--primary-color);

          &::after {
            opacity: 1;
          }
        }

        input:disabled + label {
          opacity: 0.5;
          cursor: not-allowed;
          border-color: #e5e7eb;

          &:hover {
            border-color: #e5e7eb;
          }
        }
      }

      .task-content {
        flex: 1;
        min-width: 0;

        .task-title {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
          color: var(--text-primary);
          line-height: 1.5;
          margin-bottom: 4px;
          word-wrap: break-word;

          .task-list-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            flex-shrink: 0;
          }
        }

        .task-edit-input {
          width: 100%;
          padding: 4px 8px;
          border: 1px solid #6366f1;
          border-radius: 4px;
          font-size: 14px;
          outline: none;
          background: white;
        }

        .task-meta {
          display: flex;
          align-items: center;
          gap: 8px;
          flex-wrap: wrap;
          

          .abandoned-label {
            background: #fef3c7;
            color: #d97706;
            border: 1px solid #d97706;
            font-size: 11px;
            padding: 1px 6px;
            border-radius: 3px;
            font-weight: 500;
            flex-shrink: 0;
          }

          .priority-badge {
            font-size: 11px;
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-weight: 500;
          }

          .pomodoro-count,
          .due-date,
          .recurrence {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 11px;
            color: #64748b;
            background: #f8fafc;
            padding: 2px 6px;
            border-radius: 4px;

            svg {
              flex-shrink: 0;
            }
          }

          .due-date.overdue {
            color: #dc2626;
            background-color: #fee2e2;
          }
        }
      }

      .task-actions {
        display: flex;
        align-items: center;
        gap: 4px;
        opacity: 0;
        transition: opacity 0.2s ease;

        .action-btn {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 28px;
          height: 28px;
          border: none;
          background: none;
          color: #64748b;
          cursor: pointer;
          border-radius: 4px;
          transition: all 0.2s ease;

          &:hover {
            background: #f1f5f9;
            color: #475569;
          }

          &.start-btn:hover {
            background: #dbeafe;
            color: #2563eb;
          }

          &.abandon-btn:hover {
            background: #fef3c7;
            color: #d97706;
          }

          &.restore-btn:hover {
            background: #dcfce7;
            color: #16a34a;
          }

          &.delete-btn:hover {
            background: #fee2e2;
            color: #dc2626;
          }
        }
      }
    }

    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 60px 20px;
      text-align: center;
      color: #94a3b8;

      svg {
        margin-bottom: 16px;
        opacity: 0.5;
      }

      p {
        margin: 0 0 4px 0;
        font-size: 16px;
        font-weight: 500;
      }

      span {
        font-size: 14px;
        opacity: 0.8;
      }
    }
  }
}

// 搜索区域样式
.search-section {
  padding: 15px 15px 0 15px;

  .search-controls {
    display: flex;
    gap: 12px;
    align-items: center;
    margin-bottom: 12px;
  }

  .search-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    background: var(--surface-color);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 0 12px;
    transition: all 0.2s ease;
    flex: 1;

    &:focus-within {
      border-color: #3b82f6;
      background: white;
      box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }

    .search-icon {
      color: #64748b;
      margin-right: 8px;
      flex-shrink: 0;
    }

    .search-input {
      flex: 1;
      border: none;
      background: transparent;
      padding: 10px 0;
      font-size: 14px;
      color: var(--text-primary);
      outline: none;

      &::placeholder {
        color: #94a3b8;
      }
    }

    .clear-search-btn {
      background: none;
      border: none;
      padding: 4px;
      cursor: pointer;
      color: #64748b;
      border-radius: 4px;
      transition: all 0.2s ease;
      margin-left: 8px;
      flex-shrink: 0;

      &:hover {
        background-color: var(--surface-color);
        color: var(--text-primary);
      }
    }
  }

  .filter-controls {
    display: flex;
    gap: 8px;
    align-items: center;
  }

  .sort-wrapper {
    display: flex;
    align-items: center;
    background: var(--surface-color);
    border: 1px solid var(--border-color);
    border-radius: 6px;
    padding: 0 8px;
    gap: 6px;

    .sort-icon {
      color: #64748b;
      flex-shrink: 0;
    }

    .sort-select {
      border: none;
      background: transparent;
      padding: 8px 4px;
      font-size: 13px;
      color: var(--text-primary);
      outline: none;
      cursor: pointer;
      min-width: 80px;
    }
  }

  .sort-direction-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    background: var(--surface-color);
    border: 1px solid var(--border-color);
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s ease;
    color: #64748b;

    &:hover {
      background: #f1f5f9;
      border-color: #cbd5e1;
      color: var(--text-primary);
    }
  }

  .filter-btn {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    background: var(--surface-color);
    border: 1px solid var(--border-color);
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s ease;
    color: #64748b;

    &:hover {
      background: #f1f5f9;
      border-color: #cbd5e1;
      color: var(--text-primary);
    }

    &.active {
      background: #dbeafe;
      border-color: #3b82f6;
      color: #3b82f6;
    }

    .filter-count {
      position: absolute;
      top: -6px;
      right: -6px;
      background: #ef4444;
      color: white;
      font-size: 10px;
      font-weight: 600;
      min-width: 16px;
      height: 16px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 4px;
    }
  }

  .filter-panel {
    background: white;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    padding: 20px;
    margin-top: 12px;
    box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
    animation: slideDown 0.2s ease-out;

    .filter-row {
      display: flex;
      gap: 32px;
      margin-bottom: 20px;
      flex-wrap: wrap;
    }

    .filter-group {
      flex: 1;
      min-width: 220px;
      background: #f8fafc;
      border-radius: 8px;
      padding: 16px;
      border: 1px solid #f1f5f9;

      > label {
        display: block;
        font-size: 14px;
        font-weight: 600;
        color: #334155;
        margin-bottom: 12px;
        display: flex;
        align-items: center;
        gap: 6px;

        &::before {
          content: '';
          width: 3px;
          height: 14px;
          background: linear-gradient(135deg, #3b82f6, #1d4ed8);
          border-radius: 2px;
        }
      }
    }

    .checkbox-group {
      display: flex;
      flex-direction: row;
      gap: 10px;
    }

    .checkbox-item {
      display: flex;
      align-items: center;
      gap: 10px;
      cursor: pointer;
      font-size: 13px;
      color: #64748b;
      padding: 6px 8px;
      border-radius: 6px;

      input[type="checkbox"] {
        width: 16px;
        height: 16px;
        cursor: pointer;
        accent-color: #3b82f6;
      }

      .priority-high {
        color: #ef4444;
        font-weight: 600;
        text-shadow: 0 1px 2px rgba(239, 68, 68, 0.1);
      }

      .priority-medium {
        color: #f59e0b;
        font-weight: 600;
        text-shadow: 0 1px 2px rgba(245, 158, 11, 0.1);
      }

      .priority-low {
        color: #10b981;
        font-weight: 600;
        text-shadow: 0 1px 2px rgba(16, 185, 129, 0.1);
      }
    }

    .date-range {
      display: flex;
      align-items: center;
      gap: 12px;
      flex-wrap: wrap;

      input[type="date"] {
        padding: 8px 12px;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        font-size: 13px;
        color: #374151;
        background: white;
        transition: all 0.2s ease;
        min-width: 140px;

        &:focus {
          outline: none;
          border-color: #3b82f6;
          box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
          transform: translateY(-1px);
        }

        &:hover {
          border-color: #9ca3af;
        }
      }

      span {
        font-size: 13px;
        color: #6b7280;
        font-weight: 500;
      }
    }

    .filter-actions {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      padding-top: 16px;
      border-top: 1px solid #f1f5f9;

      .btn {
        padding: 8px 16px;
        border-radius: 6px;
        font-size: 13px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        border: none;
        position: relative;
        overflow: hidden;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: -100%;
          width: 100%;
          height: 100%;
          background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
          transition: left 0.5s;
        }

        &:hover::before {
          left: 100%;
        }

        &.btn-secondary {
          background: #f8fafc;
          border: 1px solid #e2e8f0;
          color: #64748b;

          &:hover {
            background: #f1f5f9;
            color: #475569;
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
          }
        }

        &.btn-primary {
          background: linear-gradient(135deg, #3b82f6, #1d4ed8);
          color: white;
          box-shadow: 0 2px 4px rgba(59, 130, 246, 0.2);

          &:hover {
            background: linear-gradient(135deg, #2563eb, #1e40af);
            transform: translateY(-1px);
            box-shadow: 0 6px 12px rgba(59, 130, 246, 0.3);
          }
        }
      }
    }
  }

  @keyframes slideDown {
    from {
      opacity: 0;
      transform: translateY(-10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  .search-results-info {
    margin-top: 8px;
    font-size: 12px;
    color: #64748b;
    padding-left: 4px;
  }
}

// 游客模式提示样式
.guest-notice {
  margin: 16px 0;
  padding: 12px 16px;
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  border: 1px solid #f59e0b;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;

  .notice-content {
    display: flex;
    align-items: center;
    gap: 8px;
    flex: 1;

    .notice-icon {
      color: #d97706;
      flex-shrink: 0;
    }

    .notice-text {
      font-size: 14px;
      color: #92400e;
      font-weight: 500;
    }
  }

  .notice-login-btn {
    background: #f59e0b;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    white-space: nowrap;

    &:hover {
      background: #d97706;
      transform: translateY(-1px);
    }
  }
}

// 对话框样式
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background-color: var(--background-color);
  border-radius: 12px;
  width: 400px;
  max-width: 90vw;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1),
    0 10px 10px -5px rgba(0, 0, 0, 0.04);

  &.task-detail-dialog {
    width: 500px;
  }

  .dialog-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px 16px;
    border-bottom: 1px solid var(--border-color);

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: var(--text-primary);
    }

    .close-btn {
      background: none;
      border: none;
      padding: 4px;
      cursor: pointer;
      color: var(--text-primary);
      border-radius: 4px;
      transition: all 0.2s ease;

      &:hover {
        background-color: var(--surface-color);
        color: var(--text-primary);
      }
    }
  }

  .dialog-body {
    padding: 20px 24px;
    display: flex;
    flex-direction: column;
    gap: 15px;

    p {
      margin: 0;
      color: #374151;
      line-height: 1.5;
    }

    .form-group {

      &:last-child {
        margin-bottom: 0;
      }

      label {
        display: block;
        margin-bottom: 6px;
        font-size: 14px;
        font-weight: 500;
        color: #374151;
      }

      input,
      select,
      textarea {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        font-size: 14px;
        transition: all 0.2s ease;

        &:focus {
          outline: none;
          border-color: #6366f1;
          box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
        }
      }

      textarea {
        resize: vertical;
        min-height: 60px;
      }
    }

    .form-row {
      display: flex;
      gap: 16px;

      .form-group {
        flex: 1;
      }
    }
  }
}

// 魔法规划按钮动画
@keyframes magicGradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

// 魔法规划弹窗样式
.magic-planning-modal {
  background: var(--surface-color);
  border-radius: 20px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(255, 255, 255, 0.1);
  max-width: 650px;
  width: 90vw;
  max-height: 90vh;
  overflow: hidden;
  animation: modalSlideIn 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  backdrop-filter: blur(10px);

  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24px 28px 20px;
    border-bottom: 1px solid var(--border-color);
    background: linear-gradient(
      135deg,
      rgba(139, 92, 246, 0.08),
      rgba(6, 182, 212, 0.08),
      rgba(16, 185, 129, 0.08)
    );
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 1px;
      background: linear-gradient(
        90deg,
        transparent,
        rgba(139, 92, 246, 0.3),
        rgba(6, 182, 212, 0.3),
        rgba(16, 185, 129, 0.3),
        transparent
      );
    }

    .modal-title {
      display: flex;
      align-items: center;
      gap: 12px;
      font-size: 20px;
      font-weight: 700;
      color: var(--text-primary);
      background: linear-gradient(
        135deg,
        #8b5cf6,
        #06b6d4,
        #10b981
      );
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;

      .magic-icon {
        flex-shrink: 0;
        filter: drop-shadow(0 2px 4px rgba(139, 92, 246, 0.2));
      }
    }

    .modal-close {
      background: none;
      border: none;
      padding: 8px;
      border-radius: 8px;
      color: var(--text-secondary);
      cursor: pointer;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        inset: 0;
        border-radius: 8px;
        background: linear-gradient(135deg, #8b5cf6, #06b6d4);
        opacity: 0;
        transition: opacity 0.3s ease;
      }
      
      svg {
        position: relative;
        z-index: 1;
      }

      &:hover {
        color: white;
        transform: scale(1.1);
        
        &::before {
          opacity: 1;
        }
      }
    }
  }

  .modal-content {
    padding: 28px;
    max-height: calc(90vh - 140px);
    overflow-y: auto;

    h4 {
      margin: 0 0 16px 0;
      font-size: 16px;
      font-weight: 700;
      color: var(--text-primary);
      position: relative;
      padding-left: 12px;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 20px;
        background: linear-gradient(135deg, #8b5cf6, #06b6d4);
        border-radius: 2px;
      }
    }

    .suggestions-section {
      margin-bottom: 28px;

      .suggestion-buttons {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;

        .suggestion-btn {
          padding: 12px 20px;
          border: 2px solid transparent;
          border-radius: 25px;
          background: var(--background-color);
          color: var(--text-secondary);
          font-size: 14px;
          font-weight: 500;
          cursor: pointer;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          position: relative;
          overflow: hidden;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
          
          &::before {
            content: '';
            position: absolute;
            inset: 0;
            background: linear-gradient(135deg, #8b5cf6, #06b6d4, #10b981);
            opacity: 0;
            transition: opacity 0.3s ease;
            border-radius: 23px;
          }
          
          span {
            position: relative;
            z-index: 1;
          }

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(139, 92, 246, 0.2);
            border-color: rgba(139, 92, 246, 0.3);
            color: var(--text-primary);
          }

          &.active {
            color: white;
            transform: translateY(-1px);
            box-shadow: 0 6px 16px rgba(139, 92, 246, 0.4);
            
            &::before {
              opacity: 1;
            }
          }
        }
      }
    }

    .input-section {
      margin-bottom: 28px;

      .custom-input {
        width: 100%;
        padding: 16px 20px;
        border: 2px solid var(--border-color);
        border-radius: 12px;
        background: var(--background-color);
        color: var(--text-primary);
        font-size: 15px;
        font-family: inherit;
        resize: vertical;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        min-height: 80px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

        &:focus {
          outline: none;
          border-color: #8b5cf6;
          box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.1), 0 4px 12px rgba(139, 92, 246, 0.15);
          transform: translateY(-1px);
        }

        &::placeholder {
          color: var(--text-secondary);
          opacity: 0.7;
        }
      }
    }

    .list-options-section {
      margin-bottom: 24px;

      .option-item {
        padding: 20px;
        background: var(--surface-color);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        transition: all 0.3s ease;

        &:hover {
          border-color: rgba(139, 92, 246, 0.3);
          box-shadow: 0 4px 12px rgba(139, 92, 246, 0.1);
        }

        .switch-label {
          display: flex;
          align-items: center;
          gap: 12px;
          cursor: pointer;
          margin-bottom: 8px;

          .switch-input {
            position: relative;
            width: 44px;
            height: 24px;
            appearance: none;
            background: var(--border-color);
            border-radius: 12px;
            transition: all 0.3s ease;
            cursor: pointer;

            &:checked {
              background: #8b5cf6;
            }

            &::before {
              content: '';
              position: absolute;
              top: 2px;
              left: 2px;
              width: 20px;
              height: 20px;
              background: white;
              border-radius: 50%;
              transition: all 0.3s ease;
              box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            }

            &:checked::before {
              transform: translateX(20px);
            }
          }

          .switch-text {
            font-size: 15px;
            font-weight: 500;
            color: var(--text-primary);
          }
        }

        .option-description {
          font-size: 13px;
          color: var(--text-secondary);
          line-height: 1.5;
          margin: 0;
          margin-left: 56px;
        }
      }
    }

    .explanation-section {
      .explanation-card {
        display: flex;
        gap: 16px;
        padding: 20px;
        background: linear-gradient(
          135deg,
          rgba(139, 92, 246, 0.05),
          rgba(6, 182, 212, 0.05),
          rgba(16, 185, 129, 0.05)
        );
        border: 2px solid transparent;
        border-radius: 12px;
        position: relative;
        overflow: hidden;
        
        &::before {
          content: '';
          position: absolute;
          inset: 0;
          padding: 2px;
          background: linear-gradient(135deg, #8b5cf6, #06b6d4, #10b981);
          border-radius: 12px;
          mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
          mask-composite: exclude;
          opacity: 0.3;
        }

        .info-icon {
          color: #8b5cf6;
          flex-shrink: 0;
          margin-top: 2px;
          filter: drop-shadow(0 1px 2px rgba(139, 92, 246, 0.2));
        }

        .explanation-text {
          font-size: 14px;
          line-height: 1.6;

          p {
            margin: 0 0 10px 0;
            color: var(--text-secondary);

            &:last-child {
              margin-bottom: 0;
            }

            strong {
              color: var(--text-primary);
              font-weight: 700;
            }
          }
        }
      }
    }
  }

  .modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 16px;
    padding: 20px 28px;
    border-top: 1px solid var(--border-color);
    background: linear-gradient(
      135deg,
      rgba(139, 92, 246, 0.02),
      rgba(6, 182, 212, 0.02),
      rgba(16, 185, 129, 0.02)
    );
    backdrop-filter: blur(5px);

    .btn {
      padding: 12px 24px;
      border-radius: 10px;
      font-weight: 600;
      font-size: 14px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      position: relative;
      overflow: hidden;
      
      &.btn-secondary {
        background: var(--surface-color);
        border: 2px solid var(--border-color);
        color: var(--text-secondary);
        
        &:hover {
          background: var(--background-color);
          border-color: #8b5cf6;
          color: var(--text-primary);
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
      }
    }

    .magic-generate-btn {
      display: flex;
      align-items: center;
      gap: 8px;
      background: linear-gradient(135deg, #8b5cf6, #06b6d4, #10b981);
      border: none;
      color: white;
      box-shadow: 0 4px 12px rgba(139, 92, 246, 0.3);
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(
          90deg,
          transparent,
          rgba(255, 255, 255, 0.2),
          transparent
        );
        transition: left 0.5s ease;
      }
      
      &:hover:not(:disabled) {
        transform: translateY(-2px) scale(1.02);
        box-shadow: 0 8px 20px rgba(139, 92, 246, 0.4);
        
        &::before {
          left: 100%;
        }
      }

      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        transform: none;
        
        &:hover {
          transform: none;
          box-shadow: 0 4px 12px rgba(139, 92, 246, 0.3);
        }
      }

      .loading-icon {
        animation: spin 1s linear infinite;
      }

      .magic-wand {
        flex-shrink: 0;
        filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.1));
      }
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 游客模式限制弹窗样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
  animation: fadeIn 0.3s ease-out;
}

.guest-limit-modal {
  background: var(--surface-color);
  border-radius: 12px;
  box-shadow: var(--shadow-color);
  max-width: 480px;
  width: 90vw;
  max-height: 90vh;
  overflow: hidden;
  animation: modalSlideIn 0.3s ease-out;
  position: relative;

  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px 16px;
    border-bottom: 1px solid var(--border-color);

    .modal-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 18px;
      font-weight: 600;
      color: var(--text-primary);

      .warning-icon {
        color: #f59e0b;
        flex-shrink: 0;
      }
    }

    .modal-close {
      background: none;
      border: none;
      padding: 4px;
      border-radius: 4px;
      color: var(--text-secondary);
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover {
        background: var(--hover-bg);
        color: var(--text-primary);
      }
    }
  }

  .modal-content {
    padding: 20px 24px;

    .limit-info {
      margin-bottom: 24px;

      .limit-message {
        font-size: 16px;
        color: var(--text-primary);
        margin-bottom: 8px;

        strong {
          color: #dc2626;
          font-weight: 600;
        }
      }

      .current-count {
        font-size: 14px;
        color: var(--text-secondary);

        .count-number {
          font-weight: 600;
          color: #dc2626;
        }
      }
    }

    .benefits-list {
      h4 {
        font-size: 14px;
        font-weight: 600;
        color: var(--text-primary);
        margin-bottom: 12px;
      }

      ul {
        list-style: none;
        padding: 0;
        margin: 0;

        li {
          display: flex;
          align-items: center;
          padding: 6px 0;
          font-size: 14px;
          color: var(--text-secondary);

          &:before {
            content: "";
            width: 4px;
            height: 4px;
            background: #10b981;
            border-radius: 50%;
            margin-right: 12px;
            flex-shrink: 0;
          }
        }
      }
    }
  }

  .modal-footer {
    display: flex;
    gap: 12px;
    padding: 16px 24px 20px;
    border-top: 1px solid var(--border-color);

    .btn {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      padding: 10px 16px;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      transition: all 0.2s ease;
      cursor: pointer;

      &.btn-secondary {
        background: var(--bg-secondary);
        color: var(--text-secondary);
        border: 1px solid var(--border-color);

        &:hover {
          background: var(--hover-bg);
          color: var(--text-primary);
        }
      }

      &.btn-primary {
        background: var(--primary-color);
        color: var(--title-color);
        border: 1px solid var(--border-color);
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding: 16px 24px 20px;
  border-top: 1px solid #f1f5f9;

  .btn {
    padding: 8px 16px;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    border: none;

    &.btn-secondary {
      background-color: var(--surface-color);
      color: var(--text-secondary);

      &:hover {
        background-color: var(--surface-color);
        color: var(--text-primary);
      }
    }

    &.btn-primary {
      background-color: var(--primary-color);
      color: white;

      &:hover {
        background-color: var(--primary-hover);
      }
    }

    &.btn-danger {
      background-color: #dc2626;
      color: white;

      &:hover {
        background-color: #b91c1c;
      }
    }

    &.btn-warning {
      background-color: #d97706;
      color: white;

      &:hover {
        background-color: #b45309;
      }
    }
  }
}

// AI配置提示模态框样式
.ai-config-prompt-modal {
  background: var(--surface-color);
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  max-width: 480px;
  width: 90vw;
  animation: modalSlideIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  border: 1px solid var(--border-color);

  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px 16px;
    border-bottom: 1px solid var(--border-color);
    background: var(--background-color);

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: var(--text-primary);
    }

    .close-btn {
      background: none;
      border: none;
      padding: 8px;
      border-radius: 6px;
      color: var(--text-secondary);
      cursor: pointer;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        background: var(--hover-bg);
        color: var(--text-primary);
      }
    }
  }

  .modal-content {
    padding: 24px;
    text-align: center;
    background: var(--surface-color);

    .prompt-icon {
      margin-bottom: 20px;
      
      svg {
        filter: drop-shadow(0 2px 8px rgba(76, 175, 80, 0.3));
      }
    }

    .prompt-message {
      font-size: 16px;
      color: var(--text-primary);
      margin: 0 0 12px 0;
      line-height: 1.5;
      font-weight: 500;
    }

    .prompt-submessage {
      font-size: 14px;
      color: var(--text-secondary);
      margin: 0;
      line-height: 1.5;
    }
  }

  .modal-actions {
    display: flex;
    gap: 12px;
    padding: 20px 24px;
    border-top: 1px solid var(--border-color);
    background: var(--background-color);

    button {
      flex: 1;
      padding: 12px 20px;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s ease;
      border: 1px solid transparent;
      display: flex;
      align-items: center;
      justify-content: center;

      &.cancel-btn {
        background: var(--background-color);
        color: var(--text-secondary);
        border-color: var(--border-color);

        &:hover {
          background: var(--hover-bg);
          color: var(--text-primary);
          border-color: var(--text-secondary);
        }
      }

      &.confirm-btn {
        background: var(--primary-color);
        color: var(--title-color);
        border-color: var(--primary-color);
      }
    }
  }
}

// AI错误提示模态框样式
.ai-error-modal {
  background: var(--surface-color);
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  max-width: 480px;
  width: 90vw;
  animation: modalSlideIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  border: 1px solid var(--border-color);

  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px 16px;
    border-bottom: 1px solid var(--border-color);
    background: var(--background-color);

    .modal-title {
      display: flex;
      align-items: center;
      gap: 12px;
      font-size: 18px;
      font-weight: 600;
      color: var(--text-primary);

      .error-icon {
        flex-shrink: 0;
        filter: drop-shadow(0 2px 4px rgba(239, 68, 68, 0.2));
      }
    }

    .close-btn {
      background: none;
      border: none;
      padding: 8px;
      border-radius: 6px;
      color: var(--text-secondary);
      cursor: pointer;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        background: var(--hover-bg);
        color: var(--text-primary);
      }
    }
  }

  .modal-content {
    padding: 24px;
    text-align: center;
    background: var(--surface-color);

    .error-message {
      font-size: 16px;
      color: var(--text-primary);
      margin: 0 0 12px 0;
      line-height: 1.5;
      font-weight: 500;
    }

    .error-submessage {
      font-size: 14px;
      color: var(--text-secondary);
      margin: 0;
      line-height: 1.5;
    }
  }

  .modal-actions {
    display: flex;
    gap: 12px;
    padding: 20px 24px;
    border-top: 1px solid var(--border-color);
    background: var(--background-color);

    button {
      flex: 1;
      padding: 12px 20px;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s ease;
      border: 1px solid transparent;
      display: flex;
      align-items: center;
      justify-content: center;

      &.cancel-btn {
        background: var(--background-color);
        color: var(--text-secondary);
        border-color: var(--border-color);

        &:hover {
          background: var(--hover-bg);
          color: var(--text-primary);
          border-color: var(--text-secondary);
        }
      }

      &.confirm-btn {
        background: #ef4444;
        color: white;
        border-color: #ef4444;
      }
    }
  }
}

// 时间验证警告样式
.time-validation-warning {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: #fef3c7;
  border: 1px solid #f59e0b;
  border-radius: 8px;
  color: #92400e;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 15px;

  svg {
    flex-shrink: 0;
  }

  span {
    line-height: 1.4;
  }
}

// 重复功能帮助按钮样式
.repeat-help-btn {
  background: none;
  border: none;
  color: var(--primary-color);
  cursor: pointer;
  border-radius: 4px;
  display: inline-flex;
  align-items: center;
  justify-content: center;

  svg {
    transition: color 0.2s ease;
  }

  &:hover svg {
    color: var(--primary-hover, var(--primary-color));
  }
}

// 重复功能提示样式
.repeat-tip {
  background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
  border: 1px solid #bbdefb;
  padding: 12px 16px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  animation: slideDown 0.3s ease-out;

  .tip-content {
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;

    .tip-icon {
      color: var(--primary-color);
      flex-shrink: 0;
    }

    span {
      color: #424242;
      font-size: 14px;
      line-height: 1.4;
    }
  }

  .tip-close {
    background: none;
    border: none;
    color: #757575;
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
    flex-shrink: 0;
    margin-left: 12px;

    &:hover {
      background: rgba(0, 0, 0, 0.05);
      color: #424242;
    }
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 重复功能说明模态框样式
.repeat-help-dialog {
  max-width: 600px;
  width: 90vw;
  max-height: 80vh;
  overflow-y: auto;

  .dialog-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    background: var(--background-color);

    h3 {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 18px;
      font-weight: 600;
      color: var(--text-primary);
      margin: 0;

      .repeat-icon {
        color: var(--primary-color);
      }
    }

    .dialog-close-btn {
      background: none;
      border: none;
      color: var(--text-secondary);
      cursor: pointer;
      padding: 8px;
      border-radius: 6px;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        background: var(--hover-bg);
        color: var(--text-primary);
      }
    }
  }

  .repeat-help-content {
    padding: 24px;
    
    .help-section {
      margin-bottom: 24px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      h4 {
        font-size: 16px;
        font-weight: 600;
        color: var(--text-primary);
        margin: 0 0 12px 0;
        display: flex;
        align-items: center;
        gap: 8px;
      }
      
      p {
        font-size: 14px;
        color: var(--text-secondary);
        line-height: 1.6;
        margin: 0;
      }
    }
    
    .repeat-types {
      display: flex;
      flex-direction: column;
      gap: 12px;
      
      .repeat-type-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px;
        background: var(--surface-color);
        border-radius: 8px;
        border: 1px solid var(--border-color);
        
        .type-badge {
          padding: 4px 12px;
          border-radius: 20px;
          font-size: 12px;
          font-weight: 600;
          color: white;
          
          &.daily {
            background: linear-gradient(135deg, #10b981, #059669);
          }
          
          &.weekly {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
          }
          
          &.monthly {
            background: linear-gradient(135deg, #8b5cf6, #7c3aed);
          }
        }
        
        .type-desc {
          font-size: 14px;
          color: var(--text-secondary);
        }
      }
    }
    
    .time-rules {
      display: flex;
      flex-direction: column;
      gap: 16px;
      
      .rule-item {
        padding: 16px;
        background: var(--surface-color);
        border-radius: 8px;
        border-left: 4px solid var(--primary-color);
        
        .rule-title {
          font-size: 14px;
          font-weight: 600;
          color: var(--text-primary);
          margin-bottom: 6px;
        }
        
        .rule-desc {
          font-size: 13px;
          color: var(--text-secondary);
          line-height: 1.5;
          margin-bottom: 8px;
        }
        
        .rule-example {
          font-size: 12px;
          color: var(--primary-color);
          background: rgba(99, 102, 241, 0.1);
          padding: 8px 12px;
          border-radius: 6px;
          font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        }
      }
    }
    
    .tips-list {
      margin: 0;
      padding-left: 20px;
      
      li {
        font-size: 14px;
        color: var(--text-secondary);
        line-height: 1.6;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  .dialog-footer {
    padding: 16px 24px;
    border-top: 1px solid var(--border-color);
    background: var(--background-color);
    display: flex;
    justify-content: flex-end;
  }
}

// 重复任务时间错误模态框样式
.repeat-task-error-modal {
  background: var(--background-color);
  border-radius: 12px;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  max-width: 480px;
  width: 90%;
  max-height: 90vh;
  overflow: hidden;
  
  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    background: var(--background-color);
    
    .modal-title {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 18px;
      font-weight: 600;
      color: var(--text-primary);
      margin: 0;
      
      .warning-icon {
        color: #f59e0b;
      }
    }
    
    .close-btn {
      background: none;
      border: none;
      color: var(--text-secondary);
      cursor: pointer;
      padding: 8px;
      border-radius: 6px;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &:hover {
        background: var(--hover-bg);
        color: var(--text-primary);
      }
    }
  }
  
  .modal-content {
    padding: 24px;
    
    .error-info {
      .error-message {
        font-size: 16px;
        color: var(--text-primary);
        margin-bottom: 16px;
        font-weight: 500;
      }
      
      .task-info {
        background: var(--surface-color, #f8fafc);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 16px;
        
        p {
          margin: 0 0 8px 0;
          font-size: 14px;
          color: var(--text-secondary);
          
          &:last-child {
            margin-bottom: 0;
          }
          
          strong {
            color: var(--text-primary);
            font-weight: 600;
          }
        }
      }
      
      .error-submessage {
        font-size: 14px;
        color: var(--text-secondary);
        line-height: 1.5;
        margin: 0;
      }
    }
  }
  
  .modal-actions {
    padding: 16px 24px;
    border-top: 1px solid var(--border-color);
    background: var(--background-color);
    display: flex;
    justify-content: flex-end;
    
    .confirm-btn {
      padding: 10px 20px;
      background: var(--primary-color);
      color: white;
      border: none;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s ease;
      
      &:active {
        transform: translateY(0);
      }
    }
  }
}

/* 浮动添加按钮样式 */
.floating-add-btn {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 56px;
  height: 56px;
  background: var(--primary-color);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  z-index: 1000;
  color: white;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
    background: var(--primary-hover, #4f46e5);
  }
  
  &:active {
    transform: translateY(0);
  }
  
  svg {
    width: 24px;
    height: 24px;
  }
}

/* 添加任务Modal样式 */
.add-task-modal {
  background: var(--background-color);
  border-radius: 12px;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  max-width: 600px;
  width: 90%;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  
  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    background: var(--background-color);
    
    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: var(--text-primary);
    }
    
    .modal-close {
      background: none;
      border: none;
      color: var(--text-secondary);
      cursor: pointer;
      padding: 8px;
      border-radius: 6px;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &:hover {
        background: var(--hover-bg);
        color: var(--text-primary);
      }
    }
  }
  
  .modal-tabs {
    display: flex;
    border-bottom: 1px solid var(--border-color);
    background: var(--background-color);
    
    .tab-btn {
      flex: 1;
      padding: 12px 16px;
      background: none;
      border: none;
      font-size: 14px;
      font-weight: 500;
      color: var(--text-secondary);
      cursor: pointer;
      transition: all 0.2s ease;
      border-bottom: 2px solid transparent;
      
      &:hover {
        color: var(--text-primary);
        background: var(--hover-bg);
      }
      
      &.active {
        color: var(--primary-color);
        border-bottom-color: var(--primary-color);
        background: var(--surface-color, #f8fafc);
      }
    }
  }
  
  .modal-content {
    flex: 1;
    overflow-y: auto;
    padding: 24px;
    
    .add-task-wrapper {
      margin-bottom: 20px;
      
      .add-task-input {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px 16px;
        border: 2px solid var(--border-color);
        border-radius: 8px;
        background: var(--background-color);
        transition: all 0.2s ease;
        
        &:focus-within {
          border-color: var(--primary-color);
          box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
        }
        
        .add-icon {
          color: var(--text-secondary);
          flex-shrink: 0;
        }
        
        input {
          flex: 1;
          border: none;
          outline: none;
          background: transparent;
          font-size: 14px;
          color: var(--text-primary);
          
          &::placeholder {
            color: var(--text-secondary);
          }
        }
      }
    }
    
    .task-options {
      .option-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
        gap: 16px;
        
        .option-group {
          display: flex;
          flex-direction: column;
          gap: 6px;
          
          label {
            font-size: 12px;
            font-weight: 500;
            color: var(--text-secondary);
            display: flex;
            align-items: center;
            gap: 4px;
            
            .repeat-help-btn {
              background: none;
              border: none;
              color: var(--text-secondary);
              cursor: pointer;
              padding: 2px;
              border-radius: 4px;
              transition: all 0.2s ease;
              display: flex;
              align-items: center;
              
              &:hover {
                color: var(--primary-color);
                background: var(--hover-bg);
              }
            }
          }
          
          select, input {
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            background: var(--background-color);
            color: var(--text-primary);
            font-size: 14px;
            transition: all 0.2s ease;
            
            &:focus {
              outline: none;
              border-color: var(--primary-color);
              box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
            }
          }
        }
      }
    }
    
    /* 智能方式内容样式 */
    .suggestions-section {
      margin-bottom: 24px;
      
      h4 {
        margin: 0 0 12px 0;
        font-size: 14px;
        font-weight: 600;
        color: var(--text-primary);
      }
      
      .suggestion-buttons {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
        gap: 8px;
        
        .suggestion-btn {
          padding: 8px 12px;
          background: var(--surface-color, #f8fafc);
          border: 1px solid var(--border-color);
          border-radius: 6px;
          font-size: 12px;
          color: var(--text-secondary);
          cursor: pointer;
          transition: all 0.2s ease;
          text-align: center;
          
          &:hover {
            border-color: var(--primary-color);
            color: var(--primary-color);
          }
          
          &.active {
            background: var(--primary-color);
            border-color: var(--primary-color);
            color: white;
          }
        }
      }
    }
    
    .input-section {
      margin-bottom: 24px;
      
      .custom-input {
        width: 100%;
        padding: 12px 16px;
        border: 1px solid var(--border-color);
        border-radius: 8px;
        background: var(--background-color);
        color: var(--text-primary);
        font-size: 14px;
        line-height: 1.5;
        resize: vertical;
        min-height: 80px;
        transition: all 0.2s ease;
        
        &:focus {
          outline: none;
          border-color: var(--primary-color);
          box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
        }
        
        &::placeholder {
          color: var(--text-secondary);
        }
      }
    }
    
    .list-options-section {
      margin-bottom: 24px;
      
      .option-item {
        .switch-label {
          display: flex;
          align-items: center;
          gap: 12px;
          cursor: pointer;
          margin-bottom: 8px;
          
          .switch-input {
            display: none;
          }
          
          .switch-slider {
            position: relative;
            width: 44px;
            height: 24px;
            background: var(--border-color);
            border-radius: 12px;
            transition: all 0.3s ease;
            
            &::before {
              content: '';
              position: absolute;
              top: 2px;
              left: 2px;
              width: 20px;
              height: 20px;
              background: white;
              border-radius: 50%;
              transition: all 0.3s ease;
            }
          }
          
          .switch-input:checked + .switch-slider {
            background: var(--primary-color);
            
            &::before {
              transform: translateX(20px);
            }
          }
          
          .switch-text {
            font-size: 14px;
            font-weight: 500;
            color: var(--text-primary);
          }
        }
        
        .option-description {
          margin: 0;
          font-size: 12px;
          color: var(--text-secondary);
          line-height: 1.4;
          padding-left: 56px;
        }
      }
    }
    
    .explanation-section {
      .explanation-card {
        display: flex;
        gap: 12px;
        padding: 16px;
        background: var(--surface-color, #f8fafc);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        
        .info-icon {
          color: var(--primary-color);
          flex-shrink: 0;
          margin-top: 2px;
        }
        
        .explanation-text {
          flex: 1;
          
          p {
            margin: 0 0 8px 0;
            font-size: 14px;
            color: var(--text-primary);
            line-height: 1.5;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            strong {
              font-weight: 600;
            }
          }
        }
      }
    }
  }
  
  .modal-footer {
    padding: 16px 24px;
    border-top: 1px solid var(--border-color);
    background: var(--background-color);
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    
    .btn {
      padding: 10px 20px;
      border: none;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      gap: 8px;
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
      
      &.btn-secondary {
        background: var(--surface-color, #f8fafc);
        color: var(--text-secondary);
        border: 1px solid var(--border-color);
        
        &:hover:not(:disabled) {
          background: var(--hover-bg);
          color: var(--text-primary);
        }
      }
      
      &.btn-primary {
        background: var(--primary-color);
        color: white;
        
        &:hover:not(:disabled) {
          background: var(--primary-hover, #4f46e5);
        }
        
        &.magic-generate-btn {
          .loading-icon {
            animation: spin 1s linear infinite;
          }
          
          .magic-wand {
            transition: all 0.3s ease;
          }
          
          &:hover:not(:disabled) .magic-wand {
            transform: rotate(15deg);
          }
        }
      }
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
